简体   繁体   English

如何使用 jQuery 检查所有复选框?

[英]How to check all checkboxes using jQuery?

I am not expert with jQuery but I have tried to create a little script for my application.我不是 jQuery 专家,但我尝试为我的应用程序创建一个小脚本。 I want to check all checkboxes but it isn't working correctly.我想检查所有复选框,但它不能正常工作。

First I tried to use attr and after that I tried with prop but I'm doing something wrong.首先我尝试使用attr ,然后我尝试使用prop但我做错了。

I tried this first:我首先尝试了这个:

$("#checkAll").change(function(){

  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').attr('checked','checked');
  } else {
      $('input:checkbox').removeAttr('checked');
  }       
});

But this didn't work.但这没有用。

Next: This worked better than above code下一个:这比上面的代码效果更好

$("#checkAll").change(function(){

  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').prop('checked',true);
  } else {
      $('input:checkbox').prop('checked', false);
  }       
});

Both examples don't work.这两个例子都不起作用。

JSFiddle: http://jsfiddle.net/hhZfu/4/ JSFiddle:http: //jsfiddle.net/hhZfu/4/

You need to use .prop() to set the checked property您需要使用.prop()来设置选中的属性

$("#checkAll").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

Demo: Fiddle演示:小提琴

Simply use the checked property of the checkAll and use use prop() instead of attr for checked property只需使用checkAllchecked属性并使用prop()而不是 attr 来检查属性

Live Demo现场演示

 $('#checkAll').click(function () {    
     $('input:checkbox').prop('checked', this.checked);    
 });

Use prop() instead of attr() for properties like checked使用 prop() 而不是 attr() 来检查属性

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.从 jQuery 1.6 开始,.attr() 方法为尚未设置的属性返回 undefined。 To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method要检索和更改 DOM 属性,例如表单元素的选中、选择或禁用状态,请使用 .prop() 方法

You have same id for checkboxes and its should be unique .复选框的 id 相同,它应该是唯一的 You better use some class with the dependent checkboxes so that it does not include the checkboxes you do not want.您最好使用一些带有相关复选框的类,以便它不包含您不想要的复选框 As $('input:checkbox') will select all checkboxes on the page.因为$('input:checkbox')将选择页面上的所有复选框。 If your page is extended with new checkboxes then they will also get selected/un-selected.如果您的页面使用新复选框进行扩展,那么它们也将被选中/取消选中。 Which might not be the intended behaviour.这可能不是预期的行为。

Live Demo现场演示

$('#checkAll').click(function () {    
    $(':checkbox.checkItem').prop('checked', this.checked);    
});

A complete solution is here.完整的解决方案在这里。

$(document).ready(function() {
    $("#checkedAll").change(function() {
        if (this.checked) {
            $(".checkSingle").each(function() {
                this.checked=true;
            });
        } else {
            $(".checkSingle").each(function() {
                this.checked=false;
            });
        }
    });

    $(".checkSingle").click(function () {
        if ($(this).is(":checked")) {
            var isAllChecked = 0;

            $(".checkSingle").each(function() {
                if (!this.checked)
                    isAllChecked = 1;
            });

            if (isAllChecked == 0) {
                $("#checkedAll").prop("checked", true);
            }     
        }
        else {
            $("#checkedAll").prop("checked", false);
        }
    });
});

Html should be : html应该是:

Single check box on checked three checkbox will be select and deselect.选中三个复选框的单个复选框将被选中和取消选中。

<input type="checkbox" name="checkedAll" id="checkedAll" />

<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />

Hope this helps to someone as it did for me.希望这对某人有所帮助,就像对我一样。

JS Fiddle https://jsfiddle.net/52uny55w/ JS 小提琴https://jsfiddle.net/52uny55w/

I think when user select all checkbox manually then checkall should be checked automatically or user unchecked one of them from all selected checkbox then checkall should be unchecked automically.我认为当用户手动选择所有复选框时,应自动选中 checkall,或者用户从所有选中的复选框中取消选中其中一个复选框,然后应自动取消选中 checkall。 here is my code..这是我的代码..

 $('#checkall').change(function () { $('.cb-element').prop('checked',this.checked); }); $('.cb-element').change(function () { if ($('.cb-element:checked').length == $('.cb-element').length){ $('#checkall').prop('checked',true); } else { $('#checkall').prop('checked',false); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <input type="checkbox" name="all" id="checkall" />Check All</br> <input type="checkbox" class="cb-element" /> Checkbox 1</br> <input type="checkbox" class="cb-element" /> Checkbox 2</br> <input type="checkbox" class="cb-element" /> Checkbox 3

 $(document).ready(function() { $("#parent").click(function() { $(".child").prop("checked", this.checked); }); $('.child').click(function() { if ($('.child:checked').length == $('.child').length) { $('#parent').prop('checked', true); } else { $('#parent').prop('checked', false); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <p><input type="checkbox" id="parent" /> Check/Uncheck All</p> <ul> <li> <input type="checkbox" class="child" /> Checkbox 1</li> <li> <input type="checkbox" class="child" /> Checkbox 2</li> <li> <input type="checkbox" class="child" /> Checkbox 3</li> </ul>

HTML: HTML:

<p><input type="checkbox" id="parent" /> Check/Uncheck All</p>
<ul>
  <li>
    <input type="checkbox" class="child" /> Checkbox 1</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 2</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 3</li>
</ul>

jQuery: jQuery:

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child").prop("checked", this.checked);
  });

  $('.child').click(function() {
    if ($('.child:checked').length == $('.child').length) {
      $('#parent').prop('checked', true);
    } else {
      $('#parent').prop('checked', false);
    }
  });
});

Why don't you try this (in the 2nd line where 'form#' you need to put the proper selector of your html form):你为什么不试试这个(在'form#'的第二行你需要放置你的html表单的正确选择器):

$('.checkAll').click(function(){
    $('form#myForm input:checkbox').each(function(){
        $(this).prop('checked',true);
   })               
});

$('.uncheckAll').click(function(){
    $('form#myForm input:checkbox').each(function(){
        $(this).prop('checked',false);
   })               
});

Your html should be like this:你的 html 应该是这样的:

<form id="myForm">
      <span class="checkAll">checkAll</span>
      <span class="uncheckAll">uncheckAll</span>
      <input type="checkbox" class="checkSingle"></input>
      ....
</form>

I hope that helps.我希望这会有所帮助。

我知道的最简单的方法:

$('input[type="checkbox"]').prop("checked", true);

$('#checkAll').on('change', function(){
    if($(this).attr('checked')){
        $('input[type=checkbox]').attr('checked',true);
    }
    else{
        $('input[type=checkbox]').removeAttr('checked');
    }
});

One checkbox to rule them all一个复选框来统治他们

For people still looking for plugin to control checkboxes through one that's lightweight, has out-of-the-box support for UniformJS and iCheck and gets unchecked when at least one of controlled checkboxes is unchecked (and gets checked when all controlled checkboxes are checked of course) I've created a jQuery checkAll plugin .对于仍在寻找通过轻量级插件来控制复选框的人,该插件具有对 UniformJS 和 iCheck 的开箱即用支持,并且在至少一个受控复选框未选中时未选中(并在所有受控复选框被选中时被选中当然)我创建了一个jQuery checkAll 插件

Feel free to check the examples on documentation page .随意检查文档页面上的示例。


For this question example all you need to do is:对于这个问题示例,您需要做的就是:

$( "#checkAll" ).checkall({
    target: "input:checkbox"
});

Isn't that clear and simple?这不是很清楚和简单吗?

    <p id="checkAll">Check All</p>
<hr />
<input type="checkbox" class="checkItem">Item 1
<input type="checkbox" class="checkItem">Item 2
<input type="checkbox" class="checkItem">Item3

And jquery和jQuery

$(document).on('click','#checkAll',function () {
     $('.checkItem').not(this).prop('checked', this.checked);
 });

You can run .prop() on the results of a jQuery Selector directly even if it returns more than one result.您可以直接对 jQuery 选择器的结果运行.prop() ,即使它返回多个结果。 So:所以:

$("input[type='checkbox']").prop('checked', true)

my solution我的解决方案

 $(function() { $(".checkAll").click(function(){ checkwhat = $(this).data("checkwhat"); $('input:checkbox.'+checkwhat).not(this).prop('checked', this.checked); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <lablel><input type="checkbox" name="chkSelectAll" class="checkAll" data-checkwhat="chkSelect">check all group 1</lablel> <br> <input class="chkSelect" type="checkbox" name="chkSelect[]" value="1"> value 1.1<br> <input class="chkSelect" type="checkbox" name="chkSelect[]" value="2"> value 1.2<br> <input class="chkSelect" type="checkbox" name="chkSelect[]" value="3"> value 1.2<br> <br> <br> <lablel><input type="checkbox" name="chkSelectAll" class="checkAll" data-checkwhat="chkSelect2">check all group 1</lablel> <br> <input class="chkSelect2" type="checkbox" name="chkSelect[]" value="1"> value 2.1<br> <input class="chkSelect2" type="checkbox" name="chkSelect[]" value="4">value 2.1<br>

Usually you also want the master checkbox to be unchecked if at least 1 slave checkbox is unchecked and to be ckecked if all slave checkboxes are checked:通常,如果至少有 1 个从复选框未被选中,您还希望主复选框未被选中,如果所有从复选框都被选中,则被选中:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAll(masterId, slaveName) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

And if you want to enable any control (eg Remove All button or a Add Something button), when at least one checkbox is checked and disable when no checkbox is checked:如果您想启用任何控件(例如Remove All按钮或Add Something按钮),至少选中一个复选框并在未选中复选框时禁用:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes,
 * enables or disables a control when a checkbox is checked
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAllAndSwitchControl(masterId, slaveName, controlId) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        switchControl(controlId, $slave.filter(':checked').length > 0);
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

/**
 * Enables or disables a control
 * @param controlId is the control-id
 * @param enable is true, if control must be enabled, or false if not
 */
function switchControl(controlId, enable) {
    var $control = $('#' + controlId);
    if (enable) {
        $control.removeProp('disabled');
    } else {
        $control.prop('disabled', 'disabled');
    }
}

HTML HTML

<HTML>
<HEAD>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE>
</HEAD>
<BODY>
    <H2>Multiple Checkbox Select/Deselect - DEMO</H2>
<table border="1">
<tr>
    <th><input type="checkbox" id="selectall"/></th>
    <th>Cell phone</th>
    <th>Rating</th>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
    <td>BlackBerry Bold 9650</td>
    <td>2/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
    <td>Samsung Galaxy</td>
    <td>3.5/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
    <td>Droid X</td>
    <td>4.5/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
    <td>HTC Desire</td>
    <td>3/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
    <td>Apple iPhone 4</td>
    <td>5/5</td>
</tr>
</table>

</BODY>
</HTML>

jQuery Code jQuery 代码

<SCRIPT language="javascript">
$(function(){

    // add multiple select / deselect functionality
    $("#selectall").click(function () {
          $('.case').attr('checked', this.checked);
    });

    // if all checkbox are selected, check the selectall checkbox
    // and viceversa
    $(".case").click(function(){

        if($(".case").length == $(".case:checked").length) {
            $("#selectall").attr("checked", "checked");
        } else {
            $("#selectall").removeAttr("checked");
        }

    });
});
</SCRIPT>

View Demo查看演示

Click here to View Demo 点击这里查看演示

use .prop() to get the value of a property使用.prop()获取属性的值

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});

i know there are lot of answer posted here but i would like to post this for optimization of code and we can use it globally.我知道这里发布了很多答案,但我想发布这个以优化代码,我们可以在全球范围内使用它。

i tried my best我已经尽力了

/*----------------------------------------
 *  Check and uncheck checkbox which will global
 *  Params : chk_all_id=id of main checkbox which use for check all dependant, chk_child_pattern=start pattern of the remain checkboxes 
 *  Developer Guidline : For to implement this function Developer need to just add this line inside checkbox {{ class="check_all" dependant-prefix-id="PATTERN_WHATEVER_U_WANT" }}
 ----------------------------------------*/
function checkUncheckAll(chk_all_cls,chiled_patter_key){
    if($("."+chk_all_cls).prop('checked') == true){
        $('input:checkbox[id^="'+chiled_patter_key+'"]').prop('checked', 'checked');
    }else{
        $('input:checkbox[id^="'+chiled_patter_key+'"]').removeProp('checked', 'checked');
    }        
}

if($(".check_all").get(0)){
    var chiled_patter_key = $(".check_all").attr('dependant-prefix-id');

    $(".check_all").on('change',function(){        
        checkUncheckAll('check_all',chiled_patter_key);
    });

    /*------------------------------------------------------
     * this will remain checkbox checked if already checked before ajax call! :)
     ------------------------------------------------------*/
    $(document).ajaxComplete(function() {
        checkUncheckAll('check_all',chiled_patter_key);
    });
}

I hope this will help!我希望这个能帮上忙!

function checkAll(class_name) {
    $("." + class_name).each(function () { 
        if (this.checked == true) 
            this.checked = false; 
        else 
            this.checked = true; 
    }); 
}

checkall is the id of allcheck box and cb-child is the name of each checkboxes that will be checked and unchecked depend on checkall click event checkall 是所有复选框的 id,cb-child 是每个复选框的名称,将根据 checkall 点击事件选中和取消选中

$("#checkall").click(function () {
                        if(this.checked){
                            $("input[name='cb-child']").each(function (i, el) {
                                el.setAttribute("checked", "checked");
                                el.checked = true;
                                el.parentElement.className = "checked";

                            });
                        }else{
                            $("input[name='cb-child']").each(function (i, el) {
                                el.removeAttribute("checked");
                                el.parentElement.className = "";
                            });
                        }
                    });

*JAVA SCRIPT TO SELECT ALL CHECK BOX * *选择所有复选框的 JAVA 脚本 *

Best Solution.. Try it最佳解决方案.. 试试看

<script type="text/javascript">
        function SelectAll(Id) {
            //get reference of GridView control
            var Grid = document.getElementById("<%= GridView1.ClientID %>");
            //variable to contain the cell of the Grid
            var cell;

            if (Grid.rows.length > 0) {
                //loop starts from 1. rows[0] points to the header.
                for (i = 1; i < grid.rows.length; i++) {
                    //get the reference of first column
                    cell = grid.rows[i].cells[0];

                    //loop according to the number of childNodes in the cell
                    for (j = 0; j < cell.childNodes.length; j++) {
                        //if childNode type is CheckBox                 
                        if (cell.childNodes[j].type == "checkbox") {
                            //Assign the Status of the Select All checkbox to the cell checkbox within the Grid
                            cell.childNodes[j].checked = document.getElementById(Id).checked;
                        }
                    }
                }
            }
        }
    </script>

You Can use below Simple Code:您可以使用以下简单代码:

function checkDelBoxes(pForm, boxName, parent)
{
    for (i = 0; i < pForm.elements.length; i++)
        if (pForm.elements[i].name == boxName)
            pForm.elements[i].checked = parent;
}

Example for Using:使用示例:

<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', true);return false;"> Select All
</a>
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', false);return false;"> Unselect All
</a>
if(isAllChecked == 0)
{ 
    $("#select_all").prop("checked", true); 
}   

please change the above line to请将上面的行更改为

if(isAllChecked == 0)
{ 
    $("#checkedAll").prop("checked", true); 
}   

in SSR's answer and its working perfect Thank you在 SSR 的回答中,它的工作完美谢谢

if($('#chk_all').is(":checked"))
 {
    $('#'+id).attr('checked', true);
 }
else
 {
    $('#'+id).attr('checked', false);
 }  
function chek_al_indi(id)
{
    var k = id;
    var cnt_descriptiv_indictr = eval($('#cnt_descriptiv_indictr').val());
    var std_cnt = 10;

    if ($('#'+ k).is(":checked"))
    {
        for (var i = 1; i <= std_cnt; i++)  
        {
            $("#chk"+ k).attr('checked',true);  
            k = k + cnt_descriptiv_indictr;
        }
    }

    if ($('#'+ k).is(":not(:checked)"))
    {
        for (var i = 1; i <= std_cnt; i++)  
        {
            $("#chk"+ k).attr('checked',false);     
            k = k + cnt_descriptiv_indictr;
        }       
    }
}
 $('#checkall').on("click",function(){
      $('.chk').trigger("click");
   });

html : html:

    <div class="col-md-3 general-sidebar" id="CategoryGrid">
                                                    <h5>Category &amp; Sub Category <span style="color: red;">* </span></h5>
                                                    <div class="checkbox">
                                                        <label>
                                                            <input onclick="checkUncheckAll(this)" type="checkbox">
                                                            All
                                                        </label>
                                                    </div>
                                                <div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>

javascript: javascript:

function checkUncheckAll(ele) {
    if (ele.checked) {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
    else {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
}
            <pre>
            <SCRIPT language="javascript">
            $(function(){
                // add multiple select / deselect functionality
                $("#selectall").click(function () {
                      $('.case').attr('checked', this.checked);
                });

                // if all checkbox are selected, check the selectall checkbox
                // and viceversa
                $(".case").click(function(){

                    if($(".case").length == $(".case:checked").length) {
                        $("#selectall").attr("checked", "checked");
                    } else {
                        $("#selectall").removeAttr("checked");
                    }

                });
            });
            </SCRIPT>
            <HTML>
            <HEAD>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
            <TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE>
            </HEAD>
            <BODY>
            <H2>Multiple Checkbox Select/Deselect - DEMO</H2>
            <table border="1">
              <tr>
                <th><input type="checkbox" id="selectall"/></th>
                <th>Cell phone</th>
                <th>Rating</th>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
                <td>BlackBerry Bold 9650</td>
                <td>2/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
                <td>Samsung Galaxy</td>
                <td>3.5/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
                <td>Droid X</td>
                <td>4.5/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
                <td>HTC Desire</td>
                <td>3/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
                <td>Apple iPhone 4</td>
                <td>5/5</td>
              </tr>
            </table>
            </BODY>
            </HTML>
            </pre>

Trigger Click触发点击

$("#checkAll").click(function(){
    $('input:checkbox').click();
});

OR或者

$("#checkAll").click(function(){
    $('input:checkbox').trigger('click');
});

OR或者

$("#checkAll").click(function(){
    $('input:checkbox').prop('checked', this.checked);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM