简体   繁体   English

无法通过[selector] .attr和.removeattr启用/禁用复选框

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

Fiddle: 小提琴:

http://jsfiddle.net/KU29Q/1/ 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") 我已经尝试通过引用相关复选框的类和/或ID,然后使用.attr(“ disabled”,“ disabled”)或.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. 也曾尝试与[selector] .prop玩耍而无济于事。 Can someone give me a push in the right direction and/or punch me in the face to relieve my agita? 有人可以朝正确的方向推动我和/或向我猛击以减轻我的焦虑吗?

Thanks. 谢谢。

JSFIDDLE DEMO JSFIDDLE演示

  1. Use .prop() instead of .attr() 使用.prop()而不是.attr()
  2. For targeting ids use # (hash) 对于定位ID,请使用# (哈希)
  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 1.您需要在小提琴中包含jQuery

2. Your class applies to both elements, so when you use it as a selector for disabling, you disable both elements: 2.您的类适用于两个元素,因此,当您将其用作禁用选择器时,将禁用两个元素:

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

You should just use the (unique) IDs instead and remove the class selector line: 您应该只使用(唯一)ID并删除类选择器行:

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

Your updated fiddle: http://jsfiddle.net/KU29Q/2/ 您更新的小提琴: http : //jsfiddle.net/KU29Q/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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