Enable and disable element with jQuery

Question:

From the original OS question Disable / enable an input with jQuery?

I want to enable and disable elements of an HTML page (be it inputs, divs, buttons, etc.).

How can I solve it using jQuery?

Answer:

From the original OS answer Disable / enable an input with jQuery?

jQuery 1.6+

To change the disabled property you must use the .prop() function.

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

jQuery 1.5 and lower

The .prop() function .prop() n't exist, but .attr() works similarly:

Set the disabled attribute:

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

To enable again the proper method is to use .removeAttr()

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

In any version of jQuery

The current DOM object can always be trusted and is probably a bit faster than the other two options if it's just one element:

// assuming an event handler thus 'this'
this.disabled = true;

The advantage of using the .prop () or .attr () is that you can set the property for a bunch of selected items.


Note: In 1.6 there is a .removeProp() method that sounds a lot like removeAttr() , but MUST NOT BE USED in native properties like 'disabled' Excerpt from documentation:

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop () to set these properties to false instead.

Translation :

Note: Do not use this method to remove native properties, such as checked, disabled, or selected. This will completely remove the property and once removed it cannot be added back to the item. Use .prop () to set these properties to false instead.

In fact, I doubt there are many legitimate uses for this method, the boolean properties are made in such a way that you should set them to false rather than "remove" them as their "attribute" equivalents in 1.5

Scroll to Top