javascript – How to remove disabled attribute using jQuery?

javascript – How to remove disabled attribute using jQuery?

Always use the prop() method to enable or disable elements when using jQuery (see below for why).

In your case, it would be:

$(#edit).click(function(event){
   event.preventDefault();
   $(.inputDisabled).prop(disabled, false); // Element(s) are now enabled.
});

jsFiddle example here.


Why use prop() when you could use attr()/removeAttr() to do this?

Basically, prop() should be used when getting or setting properties (such as autoplay, checked, disabled and required amongst others).

By using removeAttr(), you are completely removing the disabled attribute itself – while prop() is merely setting the propertys underlying boolean value to false.

While what you want to do can be done using attr()/removeAttr(), it doesnt mean it should be done (and can cause strange/problematic behaviour, as in this case).

The following extracts (taken from the jQuery documentation for prop()) explain these points in greater detail:

The difference between attributes and properties can be important in
specific situations. Before jQuery 1.6, the .attr() method sometimes
took property values into account when retrieving some attributes,
which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while
.attr() retrieves attributes.

Properties generally affect the dynamic state of a DOM element without
changing the serialized HTML attribute. Examples include the value
property of input elements, the disabled property of inputs and
buttons, or the checked property of a checkbox. The .prop() method
should be used to set disabled and checked instead of the .attr()
method. The .val() method should be used for getting and setting
value.

to remove disabled attribute use,

 $(#elementID).removeAttr(disabled);

and to add disabled attribute use,

$(#elementID).prop(disabled, true);

Enjoy 🙂

javascript – How to remove disabled attribute using jQuery?

<input type=text disabled=disabled class=inputDisabled value=>
​<button id=edit>Edit</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

$(#edit).click(function(event){
    event.preventDefault();
    $(.inputDisabled).removeAttr(disabled)
});​

http://jsfiddle.net/ZwHfY/

Leave a Reply

Your email address will not be published.