最多只能选择两个多选框的jQuery功能实现

<div class="faq_box">
                        <h3>7、希望得到更多何种类型的任务奖励?(可以选两个)</h3>
                        <ul class="clearFix">
                            <li>
                                <input type="checkbox" value="A" id="q7_1" name="q7[]" />
                                <label for="q7_1">A&nbsp;选项A</label>
                            </li>
                            <li>
                                <input type="checkbox" value="B" id="q7_2" name="q7[]" />
                                <label for="q7_2">B&nbsp;选项B</label>
                            </li>
                            <li>
                                <input type="checkbox" value="C" id="q7_3" name="q7[]" />
                                <label for="q7_3">C&nbsp;选项C</label>
                            </li>
                            <li>
                                <input type="checkbox" value="D" id="q7_4" name="q7[]" />
                                <label for="q7_4">D&nbsp;选项D</label>
                            </li>
                            <li>
                                <input type="checkbox" value="E" id="q7_5" name="q7[]" />
                                <label for="q7_5">E&nbsp;选项E</label>
                            </li>
                            <li>
                                <input type="checkbox" value="F" id="q7_6" name="q7[]" />
                                <label for="q7_6">F&nbsp;选项F</label>
                            </li>
                        </ul>
                    </div>

$(document).ready(function(){
    //第7题 只能选择两项
    $("input[id^='q7']").click(function()
    {
        limit_select_two_options(this);
    });
});   

function limit_select_two_options(obj) {
    var count=0;  
    var arr=[];  
    $("input[id^='q7']").each(function()
    {  
        if($(this).attr('checked')==true)  
        {  
            arr.push($(this));  
            count++;  
        }  
    });  

    if(count>2)  
    {  
        if($(obj).attr('value')==arr[0].attr('value'))  
        {
            arr[arr.length-1].attr('checked',false);  
        }  
       else  
        {  
            arr[0].attr('checked',false);
        }  
    }  
    return true;  
}

原文地址:https://www.cnblogs.com/xiaohong/p/2361358.html