Reputation: 13717
This code is a direct copy-paste from the jquery#faq page
<select id="x" style="width:200px;">
<option>one</option>
<option>two</option>
</select>
<input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
<input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>
The select
option list is getting disabled on first click to disable
, but not getting enabled again on clicking the Enable
button.
Please let me know, what is wrong with above piece of code?
I am using Chrome 23.0.1271.64 on windows.
Upvotes: 0
Views: 167
Reputation: 196306
The problem is the jQuery page
They say to use $('#x').attr('disabled')
but if you see the actual code that runs, it is $('#x').attr('disabled','')
This sets the disabled
attribute to an empty string. But that means that the attribute remains, and the correct usage of this attribute is for the element to be considered disabled if the attribute exists at all.
The proper way to do it is to use .prop
and use directly true
/false
values with it as @Kurt showed..
Upvotes: 1
Reputation: 3877
You are correct about there being a bug on the official jQuery page. Viewing the source for that page shows that this is the actual code:
<select id="x" style="width:200px;" disabled="disabled">
<option>one</option>
<option>two</option>
</select>
<input type="button" onclick="$('#x').attr('disabled','disabled')" value="Disable">
<input type="button" onclick="$('#x').attr('disabled','')" value="Enable">
As you can see, the onclick
code is incorrect; to enable a control (according to the jQuery FAQ) the disabled
attribute should either be set to false
or removed using $(..).removeAttr()
.
Upvotes: 1
Reputation: 2581
As of jQuery 1.7, use .prop instead:
$('#x').prop('disabled', true);
$('#x').prop('disabled', false);
Although, as mentioned by others it seems it appears to work correctly:
Upvotes: 3