简体   繁体   中英

Unable to enable/disable checkbox via [selector].attr & .removeattr

Fiddle:

http://jsfiddle.net/KU29Q/1/

Goal is to be able to enable and disable a checkbox dynamically. I've tried by referencing the class and/OR id of the checkboxes in question and then use .attr("disabled", "disabled") or .removeAttr("disabled")

<input id="check" type="checkbox" disabled="disabled" class="enableDisable"><label for="check2" >Initially Disabled</label>
<input id="check2" type="checkbox"  class="enableDisable"><label for="check2" >Initially Enabled</label>

//attempt to ENABLE checkbox1
$("check").removeAttr('disabled');

//attempt to change state of second checkbox - DISABLE it...
$(".enableDisable").attr("disabled","disabled");
$("#check2").attr("disabled", "disabled");

Also have tried playing around with [selector].prop to no avail. Can someone give me a push in the right direction and/or punch me in the face to relieve my agita?

Thanks.

JSFIDDLE DEMO

  1. Use .prop() instead of .attr()
  2. For targeting ids use # (hash)
  3. For classes use . (dot)

//attempt to ENABLE checkbox1

$("#check").prop('disabled', false);

//attempt to change state of second checkbox - DISABLE it...

$("#check2").prop("disabled",true);

1. You need to include jQuery in your fiddle

2. Your class applies to both elements, so when you use it as a selector for disabling, you disable both elements:

$(".enableDisable").attr("disabled","disabled");

You should just use the (unique) IDs instead and remove the class selector line:

$("#check").removeAttr('disabled');
$('#check2').attr('disabled', 'disabled');

Your updated fiddle: http://jsfiddle.net/KU29Q/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM