jQuery checkbox enable/disable

jQuery - checkbox enable/disable

回答1

Change your markup slightly:

$(function() {
  enable_cb();
  $("#group1").click(enable_cb);
});

function enable_cb() {
  if (this.checked) {
    $("input.group1").removeAttr("disabled");
  } else {
    $("input.group1").attr("disabled", true);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="frmChkForm" id="frmChkForm">
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>
  <input type="checkbox" name="chk9[120]" class="group1"><br>
  <input type="checkbox" name="chk9[140]" class="group1"><br>
  <input type="checkbox" name="chk9[150]" class="group1"><br>
</form>

评论

you can use .prop() instead of .attr(). May 28 '12 at 3:47
I had problems with .prop(), it worked on initial set, but if I toggled back and forth, the second time it failed to "disable" the checkbox. I stuck with attr().
– ProVega
May 26 '13 at 20:46
 
 
回答2

This is the most up-to-date solution.

<form name="frmChkForm" id="frmChkForm">
    <input type="checkbox" name="chkcc9" id="group1" />Check Me
    <input type="checkbox" name="chk9[120]" class="group1" />
    <input type="checkbox" name="chk9[140]" class="group1" />
    <input type="checkbox" name="chk9[150]" class="group1" />
</form>

$(function() {
    enable_cb();
    $("#group1").click(enable_cb);
});

function enable_cb() {
    $("input.group1").prop("disabled", !this.checked);
}

Here is the usage details for .attr() and .prop().

jQuery 1.6+

Use the new .prop() function:

$("input.group1").prop("disabled", true);
$("input.group1").prop("disabled", false);

jQuery 1.5 and below

The .prop() function is not available, so you need to use .attr().

To disable the checkbox (by setting the value of the disabled attribute) do

$("input.group1").attr('disabled','disabled');

and for enabling (by removing the attribute entirely) do

$("input.group1").removeAttr('disabled');

Any version of jQuery

If you're working with just one element, it will always be fastest to use DOMElement.disabled = true. The benefit to using the .prop() and .attr() functions is that they will operate on all matched elements.

// Assuming an event handler on a checkbox
if (this.disabled)

ref: Setting "checked" for a checkbox with jQuery?

原文地址:https://www.cnblogs.com/chucklu/p/15714474.html