Discussion on checkbox in jQuery

  • 2021-07-09 07:12:55
  • OfStack

1 starting code:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> Check box </title>
  <script src="https://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
  <script type="text/javascript">
  $(function() {
    $("#all").click(function () {
      if (this.checked) {
        $("#list :checkbox").each(function () {
          $(this).attr("checked", true);  // Selectors should be separated by spaces 
        })
      } else {
        $("#list :checkbox").each(function () {
          $(this).attr("checked", false);
        })
      }

    });
  })
</script>
</head>
<body>
<ul id="list">
  <li><label><input type="checkbox" value="1"> Guangdong Province  </label></li>
  <li><label><input type="checkbox" value="2"> Guangxi province  </label></li>
  <li><label><input type="checkbox" value="3"> Henan Province  </label></li>
  <li><label><input type="checkbox" value="4"> Fujian Province  </label></li>
  <li><label><input type="checkbox" value="5"> Hunan Province  </label></li>
  <li><label><input type="checkbox" value="6"> Jiangxi Province  </label></li>
</ul>
<input type="checkbox" id="all">
<input type="button" value=" All selection " class="btn" id="selectAll">
<input type="button" value=" Do not choose at all " class="btn" id="unSelect">
<input type="button" value=" Reverse selection " class="btn" id="reverse">
<input type="button" value=" Get all selected values " class="btn" id="getValue">
</body>
</html>

When using the method attr () with jQuery, there will be corresponding problems. For example, when you click the check box under id=list before clicking the check box of id=all, it will appear when you click the check box of id=all again. The previously clicked check box has not changed, but when you look at the element, you will find that the checked value of the check box will change accordingly. I checked the information once, and the problem is as follows:

It turned out to be an jQuery version problem. Because attr () is used here, and the version of jQuery is 3.1. 0, there is a compatibility problem.

$("XXX"). attr ("attrName"); The version of jQuery uses 2.1. 1, which is a compatibility and stability problem.

jQuery API clearly states that jQuery of 1.6 + should be judged by the attributes of prop, especially checked of checkBox.

That is, the code used is as follows:


$(function() {
    $("#all").click(function () {
      if (this.checked) {
        $("#list :checkbox").each(function () {
          $(this).prop("checked", true);  // Selectors should be separated by spaces 
        })
      } else {
        $("#list :checkbox").each(function () {
          $(this).prop("checked", false);
        })
      }

    });

Give all selection and no selection in advance when using jQuery:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> Check box </title>
  <script src="https://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
  <script type="text/javascript">
  $(function() {
    $("#all").click(function () {
      if (this.checked) {
        $("#list :checkbox").each(function () {
          $(this).prop("checked", true);  // Selectors should be separated by spaces 
        })
      } else {
        $("#list :checkbox").each(function () {
          $(this).prop("checked", false);
        })
      }
    });
    // No. 1 2 Species 
//    $("#all").click(function(){
//      if(this.checked){
//        $("#list :checkbox").prop("checked", true);
//      }else{
//        $("#list :checkbox").prop("checked", false);
//      }
//    });

    // All selection 
    $("#selectAll").click(function () {
      $("#list :checkbox,#all").prop("checked", true);
    });

    // Do not choose at all 
    $("#unSelect").click(function () {
      $("#list :checkbox,#all").prop("checked", false);
    });

    // Reverse selection 
    $("#reverse").click(function () {
      $("#list :checkbox").each(function () {
//        $(this).prop("checked", !$(this).prop("checked"));
        this.checked=!this.checked;
      });

      if($('#list :checkbox:checked').length==$("#list :checkbox").length){
        $("#all").prop("checked",true);
      }
      else{
        $("#all").prop("checked",false);
      }
    });

    // Get the selected value 
    $("#getValue").click(function(){
      var valArr = new Array();
      $("#list :checkbox:checked").each(function(i){   // Judge the selected 
        valArr[i] = $(this).val();
      })
      var vals = valArr.join(',');// To a comma-separated string 
      alert(vals);
    });
  })
  </script>
</head>
<body>
<ul id="list">
  <li><label><input type="checkbox" value="1. Guangdong Province "> Guangdong Province  </label></li>
  <li><label><input type="checkbox" value="2. Guangxi province "> Guangxi province  </label></li>
  <li><label><input type="checkbox" value="3. Henan Province "> Henan Province  </label></li>
  <li><label><input type="checkbox" value="4. Fujian Province "> Fujian Province  </label></li>
  <li><label><input type="checkbox" value="5. Hunan Province "> Hunan Province  </label></li>
  <li><label><input type="checkbox" value="6. Jiangxi Province "> Jiangxi Province  </label></li>
</ul>
<input type="checkbox" id="all">
<input type="button" value=" All selection " class="btn" id="selectAll">
<input type="button" value=" Do not choose at all " class="btn" id="unSelect">
<input type="button" value=" Reverse selection " class="btn" id="reverse">
<input type="button" value=" Get all selected values " class="btn" id="getValue">
</body>
</html>

Use acoustic JS to realize all selection and all non-selection


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<script type="text/javascript">
  function checkAll(name) {
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++) {
      if((el[i].type=="checkbox") && (el[i].name==name)) {
        el[i].checked = true;
      }
    }
  }
  function clearAll(name) {
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++) {
      if((el[i].type=="checkbox") && (el[i].name==name)) {
        el[i].checked = false;
      }
    }
  }
</script>
<input type="checkbox" name="test" value="" onclick="if(this.checked==true) { checkAll('test'); } else { clearAll('test'); }" />  Alphabet all-select switch 
<input type="checkbox" name="test" value="a" /> a
<input type="checkbox" name="test" value="b" /> b
<input type="checkbox" name="test" value="c" /> c
<input type="checkbox" name="test" value="d" /> d
<input type="checkbox" name="test" value="e" /> e
<input type="checkbox" name="test" value="f" /> f
<input type="checkbox" name="test" value="g" /> g
<br>
<input type="checkbox" name="num" value="" onclick="if(this.checked==true) { checkAll('num'); } else { clearAll('num'); }" />  Digital all-select switch  <input type="checkbox" name="num" value="1" /> 1
<input type="checkbox" name="num" value="2" /> 2
<input type="checkbox" name="num" value="3" /> 3
<br><br>
<input type="button" value=" Select all letters " onclick="checkAll('test')" /> <input type="button" value=" Empty the selected letters " onclick="clearAll('test')" /> <br><br>
<input type="button" value=" Select All Numbers " onclick="checkAll('num')" /> <input type="button" value=" Empty the selected number " onclick="clearAll('num')" />
</body>
</html>

Finally insert the difference between attr () and prop ():

In jquery 1.6, a new method prop () is added, and the official explanation only has one sentence: get the attribute value of the first element in the matching element set.

As we all know, some browsers only need to write disabled and checked, while others need to write disabled = "disabled" and checked = "checked". For example, when attr ("checked") is selected to obtain the checked attribute of checkbox, the value is "checked", but it is undefined.

jq provides a new method "prop" to obtain these attributes, which is to solve this problem. Previously, when we used attr to obtain checked attributes, we returned "checked" and "". Now, when we used prop method to obtain attributes, we returned true and false.

So, when to use attr () and when to use prop ()?

1. Add the name of the attribute, which will take effect. prop () should be used;

2. There are two attributes true and false using prop ();

3. Others use attr ();

When jquery is upgraded in the project, everyone should pay attention to this!

The following are the official recommendations for the use of attr () and prop ():

Attribute/Property .attr() .prop()
accesskey
align
async
autofocus
checked
class
contenteditable
draggable
href
id
label
location ( i.e. window.location )
multiple
readOnly
rel
selected
src
tabindex
title
type
width ( if needed over .width())


Related articles: