Disable/enable an input with jQuery?
Switch the disabled state of an input field with jQuery's .prop()
method:
Applying jQuery based on version
Choosing between .prop()
and .attr()
for handling the disabled
attribute depends on your jQuery version. For 1.6 and up, .prop()
suits best, specifically dealing with boolean properties such as disabled
.
Whereas for the veteran versions (1.5 and lower), .attr()
plays the lead role:
Skirting common issues
Here are some useful tips:
-
Embrace
.prop()
: Whileelement.disabled = true/false;
changes the value directly,.prop('disabled', true/false)
keeps you within the flow of jQuery. -
Don't Use
.removeProp()
for Default Properties: Settingdisabled
tofalse
using.removeProp()
might lead you to Narnia—it erases the property instead of setting its value. -
Dealing With Specific Input Elements: To toggle the
disabled
state of a specific input, target the element using its unique identifier:$('#your_id').prop('disabled', true/false)
. -
Event Handling Issue: Events attached to an input are muted when it is disabled. To manage events, use
$('#your_id').on/off('event_name', handler)
.
Mass Toggling Action
Having various inputs ready to change their disabled
state at a moment's notice? Here's how to do it:
This is quite convenient especially handling forms where unrelated inputs rely on certain conditions.
Was this article helpful?