Solution to the problem that jquery checkbox can not be checked twice by attr of

  • 2021-07-04 18:00:29
  • OfStack

This morning, the beautiful test sister put forward a strange bug, saying that my 1 function checkbox appears and disappears. For example, if it is checked for the first time, it may not be selected for the first time.

Thinking of having intimate contact with beautiful women, the chicken immediately moved.

After even-layer cocoon stripping (da da jiang you), the reason was finally known: attr () failed when the check box was selected twice.

For example, on the following HTML page, "Check" at 1 o'clock, "Uncheck" at 2 o'clock, and "Check" at 3 o'clock. Look, it won't work.

1.html


<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>prop demo</title>
 <style>
 img {
  padding: 10px;
 }
 div {
  color: red;
  font-size: 24px;
 }
 </style>
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
 <input type="checkbox" checked="checked">
 <input type="checkbox">
 <input type="checkbox">
 <input type="checkbox" checked="checked">
 
<script>
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
 return !val;
});
</script>
 
</body>
</html>

The solution is to replace the attr () method (above Jquery 1.6) with prop (), as follows:

2.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Attr checked</title>
<script type="text/javascript" src="./js/jquery-1.11.2.js"></script>
<script type="text/javascript">
  function switchChecked(flag) {
    $("input[type='checkbox']").prop('checked', flag);
  }
</script>
</head>
<body>
  <input type="checkbox" />
  <input type="button" onclick="switchChecked(true)" value=" Select ">
  <input type="button" onclick="switchChecked(false)" value=" Uncheck ">
</body>
</html>

For official documents, see: http://api.jquery.com/attr/

Or http://api.jquery.com/prop/

Excerpts are as follows: "As of jQuery 1.6, the. attr () method returns undefined for that have been set. To retrieve and such DOM such as the checked, selected, or disabled use use use use the the


Related articles: