如何使用 jQuery 选中/取消选中带有按钮的所有复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5229023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:46:13  来源:igfitidea点击:

How do I check/uncheck all checkboxes with a button using jQuery?

jquerycheckboxuncheck

提问by Ravi

I am trying to check/uncheck all checkboxes using jQuery. Now by checking/unchecking the parent checkbox all the child checkboxes are getting selected/deselected also with the text of parent checkbox getting changed to checkall/uncheckall.

我正在尝试使用 jQuery 选中/取消选中所有复选框。现在通过选中/取消选中父复选框,所有子复选框都被选中/取消选中,父复选框的文本也被更改为选中/取消选中。

Now I want to replace parent checkbox with an input button, and change the text also on the button to checkall/uncheckall. THere is the code, can anyone please tweak the code ?

现在我想用输入按钮替换父复选框,并将按钮上的文本也更改为选中/取消选中。这是代码,任何人都可以调整代码吗?

    $( function() {
        $( '.checkAll' ).live( 'change', function() {
            $( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' );
            $( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
        });
        $( '.cb-element' ).live( 'change', function() {
            $( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' );

        });
    });


   <input type="checkbox" class="checkAll" /> <b>Check All</b>

   <input type="checkbox" class="cb-element" /> Checkbox  1
   <input type="checkbox" class="cb-element" /> Checkbox  2
   <input type="checkbox" class="cb-element" /> Checkbox  3

回答by Prakash

Try this one :

试试这个:

$(document).ready(function(){
    $('.check:button').toggle(function(){
        $('input:checkbox').attr('checked','checked');
        $(this).val('uncheck all');
    },function(){
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');        
    })
})

DEMO

演示

回答by Richard Garside

This is the shortest way I've found (needs jQuery1.6+)

这是我找到的最短方法(需要 jQuery1.6+)

HTML:

HTML:

<input type="checkbox" id="checkAll"/>

JS:

JS:

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

I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.

我使用 .prop 是因为 .attr 不适用于 jQuery 1.6+ 中的复选框,除非您已明确向输入标签添加了选中的属性。

Example-

例子-

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
    
    <fieldset>
        <legend>Loads of checkboxes</legend>
        <p><label><input type="checkbox" /> Option 1</label></p>
        <p><label><input type="checkbox" /> Option 2</label></p>
        <p><label><input type="checkbox" /> Option 3</label></p>
        <p><label><input type="checkbox" /> Option 4</label></p>
    </fieldset>
</form>

回答by Rodgers

Try This One:

试试这个:

HTML

HTML

<input type="checkbox" name="all" id="checkall" />

JavaScript

JavaScript

$('#checkall:checkbox').change(function () {
   if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
   else $('input:checkbox').removeAttr('checked');
});?

DEMO

演示

回答by Crisalin Petrovschi

Html

html

<input type="checkbox" name="select_all" id="select_all" class="checkAll" />

Javascript

Javascript

    $('.checkAll').click(function(){
    if($(this).attr('checked')){
        $('input:checkbox').attr('checked',true);
    }
    else{
        $('input:checkbox').attr('checked',false);
    }
});

回答by Michal R

Solution for toggling checkboxes using a button, compatible with jQuery 1.9+ where toogle-event is no longer available:

使用按钮切换复选框的解决方案,与 jQuery 1.9+ 兼容,其中 togle -event 不再可用

$('.check:button').click(function(){
      var checked = !$(this).data('checked');
      $('input:checkbox').prop('checked', checked);
      $(this).val(checked ? 'uncheck all' : 'check all' )
      $(this).data('checked', checked);
});

DEMO

演示

回答by Ruben Perez

Try this:

尝试这个:

$('.checkAll').on('click', function(e) {
     $('.cb-element').prop('checked', $(e.target).prop('checked'));
});

eis the event generated when you do click, and e.targetis the element clicked (.checkAll), so you only have to put the property checkedof elements with class .cb-elementlike that of element with class .checkAll`.

e是你执行时产生的事件clicke.target是元素被点击(.checkAll),所以你只需要把checked类的元素的属性.cb-element像类.checkAll`的元素的属性一样。

PS: Excuse my bad English!

PS:原谅我的英语不好!

回答by Yasir Ijaz

You can try this

你可以试试这个

    $('.checkAll').on('click',function(){
        $('.checkboxes').prop('checked',$(this).prop("checked"));
    });`

Class .checkAllis a checkbox which controls the bulk action

.checkAll是控制批量操作的复选框

回答by Code Spy

Check / Uncheck All with Intermediate property using jQuery

使用 jQuery 使用中间属性选中/取消选中所有

Get Checked Items in Array using getSelectedItems()method

使用getSelectedItems()方法获取数组中的选中项

Source Checkbox List Select / Unselect All with Indeterminate Master Check

复选框列表使用不确定的主检查选择/取消选择所有

enter image description here

在此处输入图片说明

HTML

HTML

<div class="container">
  <div class="card">
    <div class="card-header">
      <ul class="list-group list-group-flush">
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="selectAll"
            id="masterCheck"
          />
          <label class="form-check-label" for="masterCheck">
            Select / Unselect All
          </label>
        </li>
      </ul>
    </div>
    <div class="card-body">
      <ul class="list-group list-group-flush" id="list-wrapper">
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item1"
            id="item1"
          />
          <label class="form-check-label" for="item1">
            Item 1
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item2"
            id="item2"
          />
          <label class="form-check-label" for="item2">
            Item 2
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item3"
            id="item3"
          />
          <label class="form-check-label" for="item3">
            Item 3
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item4"
            id="item4"
          />
          <label class="form-check-label" for="item4">
            Item 4
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item5"
            id="item5"
          />
          <label class="form-check-label" for="item5">
            Item 5
          </label>
        </li>
        <li class="list-group-item" id="selected-values"></li>
      </ul>
    </div>
  </div>
</div>

jQuery

jQuery

  $(function() {
    // ID selector on Master Checkbox
    var masterCheck = $("#masterCheck");
    // ID selector on Items Container
    var listCheckItems = $("#list-wrapper :checkbox");

    // Click Event on Master Check
    masterCheck.on("click", function() {
      var isMasterChecked = $(this).is(":checked");
      listCheckItems.prop("checked", isMasterChecked);
      getSelectedItems();
    });

    // Change Event on each item checkbox
    listCheckItems.on("change", function() {
      // Total Checkboxes in list
      var totalItems = listCheckItems.length;
      // Total Checked Checkboxes in list
      var checkedItems = listCheckItems.filter(":checked").length;

      //If all are checked
      if (totalItems == checkedItems) {
        masterCheck.prop("indeterminate", false);
        masterCheck.prop("checked", true);
      }
      // Not all but only some are checked
      else if (checkedItems > 0 && checkedItems < totalItems) {
        masterCheck.prop("indeterminate", true);
      }
      //If none is checked
      else {
        masterCheck.prop("indeterminate", false);
        masterCheck.prop("checked", false);
      }
      getSelectedItems();
    });

    function getSelectedItems() {
      var getCheckedValues = [];
      getCheckedValues = [];
      listCheckItems.filter(":checked").each(function() {
        getCheckedValues.push($(this).val());
      });
      $("#selected-values").html(JSON.stringify(getCheckedValues));
    }
  });

回答by Rohan Kumar

Agreed with Richard Garside's short answer, but instead of using prop()in $(this).prop("checked")you can use native JS checkedproperty of checkboxlike,

同意 Richard Garside 的简短回答,但您可以使用复选框的原生 JS属性,而不是使用prop()in ,$(this).prop("checked")checked

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
    
    <fieldset>
        <legend>Loads of checkboxes</legend>
        <p><label><input type="checkbox" /> Option 1</label></p>
        <p><label><input type="checkbox" /> Option 2</label></p>
        <p><label><input type="checkbox" /> Option 3</label></p>
        <p><label><input type="checkbox" /> Option 4</label></p>
    </fieldset>
</form>

回答by Hussain

Below code will work if user select all checkboxs then check all-checkbox will be checked and if user unselect any one checkbox then check all-checkbox will be unchecked.

如果用户选择所有复选框,然后选中所有复选框,则下面的代码将起作用,如果用户取消选中任何一个复选框,则将取消选中所有复选框。

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

$(".cb-element").change(function () {
  if($(".cb-element").length==$(".cb-element:checked").length)
    $("#checkall").prop('checked', true);
  else
    $("#checkall").prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/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