通过使用JQuery选择数组中的第一个复选框来选择所有复选框值

时间:2016-01-12 04:09:07

标签: jquery checkbox

如果用户点击第一个复选框,我会尝试检查所有复选框。

HTML

 <input class="checkall" type="checkbox" id="edit-field-industry-und-45" name="field_industry[und][45]" value="45"> 
 <input class="checkall" type="checkbox" id="edit-field-industry-und-24" name="field_industry[und][24]" value="24"> 
 <input class="checkall" type="checkbox" id="edit-field-industry-und-25" name="field_industry[und][25]" value="25">
 <input class="checkall" type="checkbox" id="edit-field-industry-und-26" name="field_industry[und][26]" value="26">
 <input class="checkall" type="checkbox" id="edit-field-industry-und-27" name="field_industry[und][27]" value="27">

这是我试过的

$('#edit-field-industry-und-45').click(function(event) {  //on click 
        if(this.checked) { // check select status
            $('.checkall').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"               
            });
        }else{
            $('.checkall').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"                       
            });         
        }
    });

2 个答案:

答案 0 :(得分:2)

$('#edit-field-industry-und-45').change(function () {
        $('input[type="checkbox"]').each(function () {
            $(this).prop("checked", true);
        });
    })

答案 1 :(得分:1)

查看我的DEMO我相信你会喜欢它

<input type="checkbox" id="anchor-from"/>main

<input type="checkbox" class="checkall" id="period-daily" disabled />CheckBox2
<input type="checkbox" class="checkall" id="period-weekly"disabled />CheckBox3
<input type="checkbox" class="checkall" id="period-weekly2"disabled />CheckBox3
<input type="checkbox" class="checkall" id="period-weekly3"disabled />CheckBox3
<input type="checkbox" class="checkall" id="period-weekly4"disabled />CheckBox3




$("#anchor-from").change(function(){
                if($('#anchor-from').is(':checked'))
                {
                  $(".checkall").attr("disabled", false); 
                  $(".checkall").prop("checked", true); 

                }
                else
                {
                $(".checkall").attr("disabled", true);
                 $(".checkall").prop("checked", false); 
                }



            });