check uncheck All checkboxes with another single checkbox use jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15504643/
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 15:12:24  来源:igfitidea点击:

check uncheck All checkboxes with another single checkbox use jquery

jquerycheckbox

提问by user2187325

I use jquery-1.9.1.js In my html page, it works well for the first time.

我使用 jquery-1.9.1.js 在我的 html 页面中,它第一次运行良好。

just like http://jsfiddle.net/pzCcE/1/

就像 http://jsfiddle.net/pzCcE/1/

Can somebody help me to improve it?

有人可以帮我改进它吗?

<table id="tab1">
    <input type="checkbox" name="checkAll" id="checkAll">全選
    <input type="checkbox" name="book" id="book" value="book1">book1
    <input type="checkbox" name="book" id="book" value="book2">book2
    <input type="checkbox" name="book" id="book" value="book3">book3
    <input type="checkbox" name="book" id="book" value="book4">book4
    <input type="checkbox" name="book" id="book" value="book5">book5</table>

$(function () {
    $("#tab1 #checkAll").click(function () {
        if ($("#tab1 #checkAll").is(':checked')) {
            $("#tab1 input[type=checkbox]").each(function () {
                $(this).attr("checked", true);
            });

        } else {
            $("#tab1 input[type=checkbox]").each(function () {
                $(this).attr("checked", false);
            });
        }
    });
});

回答by j08691

Change

改变

$(this).attr("checked", true);

to

$(this).prop("checked", true);

jsFiddle example

jsFiddle 示例

I actually just answered another question that was similar to this. Per the .prop()docs:

我实际上只是回答了另一个与此类似的问题。根据.prop()文档:

The .prop() method is a convenient way to set the value of properties—especially when setting multiple properties, using values returned by a function, or setting values on multiple elements at once. It should be used when setting selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, or defaultSelected. Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.The .val() method should be used for getting and setting value.

.prop() 方法是一种设置属性值的便捷​​方法——尤其是在设置多个属性、使用函数返回的值或同时设置多个元素的值时。在设置 selectedIndex、tagName、nodeName、nodeType、ownerDocument、defaultChecked 或 defaultSelected 时应该使用它。从 jQuery 1.6 开始,这些属性不能再使用 .attr() 方法设置。它们没有相应的属性,只是属性。

属性通常会影响 DOM 元素的动态状态,而不会更改序列化的 HTML 属性。示例包括输入元素的 value 属性、输入和按钮的禁用属性或复选框的选中属性。.prop() 方法应该用于设置禁用和检查,而不是 .attr() 方法。.val() 方法应该用于获取和设置值。

回答by tymeJV

You should be using classes with the same name, ID's MUST be unique!

您应该使用同名的类,ID 必须是唯一的!

<input type="checkbox" name="checkAll" id="checkAll">全選
<input type="checkbox" name="book" class="book" value="book1">book1
<input type="checkbox" name="book" class="book" value="book2">book2
<input type="checkbox" name="book" class="book" value="book3">book3
<input type="checkbox" name="book" class="book" value="book4">book4
<input type="checkbox" name="book" class="book" value="book5">book5</table>

$(function () {
    $("#checkAll").click(function () {
        if ($("#checkAll").is(':checked')) {
            $(".book").prop("checked", true);
        } else {
            $(".book").prop("checked", false);
        }
    });
});

回答by Suhaib Janjua

As the OP requires to check uncheck all checkboxes on the basis of another checkbox id=全選.

由于 OP 需要在另一个复选框的基础上取消选中所有复选框id=全選

The solution that @j08691 is provided above is good but it lacks one thing and that is, the solution doesn't uncheck the id=全選checkbox when any other checkbox in the list goes unchecked.

@j08691 上面提供的解决方案很好,但它缺少一件事,即id=全選当列表中的任何其他复选框未选中时,该解决方案不会取消选中该复选框。

So I propose a solution that checks/unchecks all the checkboxes on the basis of id=全選checkbox and if any other checkbox is unchecked then checkbox id=全選goes unchecked. And if user manually clicks on all the other check boxes then check box id=全選should also be checked to reflect the relationship.

因此,我提出了一个解决方案,该解决方案基于id=全選复选框选中/取消选中所有复选框,如果未选中任何其他复选框,则取消选中复选框id=全選。如果用户手动单击所有其他复选框,则id=全選还应选中复选框以反映关系。

OP using the same id for multiple checkboxes which is against the rules of DOM. Element IDs should be unique within the entire document.

OP 对多个复选框使用相同的 id,这违反了 DOM 规则。元素 ID 在整个文档中应该是唯一的。



So the following code covers all the aspects of this kind of scenario.

所以下面的代码涵盖了这种场景的所有方面。

HTML

HTML

<table>
    <tr>
        <td>
        <input type="checkbox" name="checkAll" id="checkAll">全選 (ALL)
        <input type="checkbox" name="book" id="book_1" value="book1">book1
        <input type="checkbox" name="book" id="book_2" value="book2">book2
        <input type="checkbox" name="book" id="book_3" value="book3">book3
        <input type="checkbox" name="book" id="book_4" value="book4">book4
        <input type="checkbox" name="book" id="book_5" value="book5">book5
        </td>
     </tr>
</table>

JQuery

查询

$(document).ready(function() {

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

    $("[id*=book_]").change(function () {
        if ($('input[id*=book_][type=checkbox]:checked').length == $('input[id*=book_][type=checkbox]').length) {
            $('#checkAll').prop('checked', true);
        } else {
            $('#checkAll').prop('checked', false);
        }
    });

});

Description of attribute selector [name*="value"]

属性选择器说明 [name*="value"]

Selects elements that have the specified attribute with a value containing a given substring.

选择具有包含给定子字符串的值的指定属性的元素。

So $('#checkAll')returns me the parent checkbox only, on which I check/uncheck all checkboxes.

所以只$('#checkAll')返回父复选框,我选中/取消选中所有复选框。

And $('[id$=book_]')returns me all the checkbox except the parent(全選) checkbox. Then on the basis of parent checkbox I check/uncheck all the other checkboxes.

$('[id$=book_]')返回除父(全选)复选框之外的所有复选框。然后在父复选框的基础上,我选中/取消选中所有其他复选框。



I also checks the length of the checkboxes other then parent(全選) checkbox, If all the other checkboxes are check then I check the parent(全選) checkbox. So this is the way to cross check all possible condition and never misses any scenario.

我还检查了除父(全选)复选框之外的复选框的长度,如果所有其他复选框都被选中,那么我检查父(全选)复选框。因此,这是交叉检查所有可能条件并且不会错过任何场景的方法。

Demo working JSFiddle here.

演示在此处使用 JSFiddle。

回答by Hannes Ledl

the fastest way. and save some lines

最快的方式。并保存一些行

   $(".ulPymnt input[type=checkbox]").each(function(){                
       $(this).prop("checked", !$(this).prop("checked"))                
   })

回答by Didac Montero

I've just simplified @j08691 answer

我刚刚简化了@j08691 答案

$("#checkAll").click(function() {
      var allChecked = $(this);
      $("#tab1 input[type=checkbox]").each(function() {
        $(this).prop("checked", allChecked.is(':checked'));
      })
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tab1">
  <tr>
    <td>
      <input type="checkbox" name="checkAll" id="checkAll">Select all
      <input type="checkbox" name="book" id="book" value="book1">book1
      <input type="checkbox" name="book" id="book" value="book2">book2
      <input type="checkbox" name="book" id="book" value="book3">book3
    </td>
  </tr>
</table>

回答by azhar

`change click to ch  $("#checkAll").click(); to $("#checkAll").change();

> Blockquote

$(function () {
 $("#checkAll").change(function () {
  if ($("#checkAll").is(':checked')) {
   $(".book").prop("checked", true);
   } else {
   $(".book").prop("checked", false);
  }
 });
});`

回答by Maxence Cupper

This one work for all checkbox lists. just add "check-all" to the input controlling that, which must have the same name

这一项适用于所有复选框列表。只需将“check-all”添加到控制该输入的输入中,该输入必须具有相同的名称

$(function() {
  $('.check-all').each(function(){
    var checkListName = $(this).attr('name');
    $(this).change(function(){
      //change all checkbox of the list checked status
      $('input[name="'+checkListName+'"]').prop('checked', $(this).prop('checked')); 
    });
    $('input[name="'+checkListName+'"]').change(function(){
      //change .check-all checkbox depending of the list checked status
      $('input[name="'+checkListName+'"].check-all').prop('checked', ($('input[name="'+checkListName+'"]:checked').not('.check-all').length == $('input[name="'+checkListName+'"]').not('.check-all').length));
    });
  });
});

回答by sasi

With answer of j08691 look into following thing also..

随着 j08691 的回答也看看下面的事情..

It totally makes no sense to create a selector like #id #id because an ID has to be unique within your DOM by definition.

创建像 #id #id 这样的选择器完全没有意义,因为根据定义,ID 在 DOM 中必须是唯一的。

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

$("#tab1 .checkAll").click(function () {

回答by Thivya

Add this too....FOR..... if one checkbox (id:book) is unselected means it will cause the main check box (id:checkAll) to be unselected

也添加这个....FOR..... 如果一个复选框 (id:book) 未被选中意味着它将导致主复选框 (id:checkAll) 被取消选中

$("#tab1 #book").click(function () {
  if($('#book').is(':checked'))
  {
    $("#checkAll").prop("checked", false);        
  }
});

回答by Thomas Wood

$("input[name='select_all_photos']").click(function () {
        var checked = $(this).is(':checked');
        $("input[name^='delete_']").each(function () {
            $(this).prop("checked", checked);
        });
    });

Don't bother doing an if statement.

不要费心做一个 if 语句。