patternjavascriptCritical
Disable/enable an input with jQuery?
Viewed 0 times
inputwithdisablejqueryenable
Problem
$input.disabled = true;or
$input.disabled = "disabled";Which is the standard way? And, conversely, how do you enable a disabled input?
Solution
jQuery 1.6+
To change the
jQuery 1.5 and below
The
Set the disabled attribute.
To enable again, the proper method is to use
In any version of jQuery
You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:
The advantage to using the
Note: In 1.6 there is a
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.
In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5
To change the
disabled property you should use the .prop() function.$("input").prop('disabled', true);
$("input").prop('disabled', false);jQuery 1.5 and below
The
.prop() function doesn't exist, but .attr() does similar: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
You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:
// assuming an event handler thus 'this'
this.disabled = true;The advantage to using the
.prop() or .attr() methods 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 it SHOULD NOT BE USED on native properties like 'disabled' Excerpt from the 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.
In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5
Code Snippets
$("input").prop('disabled', true);
$("input").prop('disabled', false);$("input").attr('disabled','disabled');$("input").removeAttr('disabled');// assuming an event handler thus 'this'
this.disabled = true;Context
Stack Overflow Q#1414365, score: 4169
Revisions (0)
No revisions yet.