Explain Codes LogoExplain Codes Logo

Disable/enable an input with jQuery?

javascript
jquery
input
event-handling
Alex KataevbyAlex Kataev·Aug 14, 2024
TLDR

Switch the disabled state of an input field with jQuery's .prop() method:

// "I'm too tired to type..." - input field probably $('#inputId').prop('disabled', true); // "I'm ready, hit me your keystrokes!" - re-energized input field $('#inputId').prop('disabled', false);

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:

// Field mode: Do Not Disturb $('input').attr('disabled', 'disabled'); // Field mode: Disturb Me $('input').removeAttr('disabled');

Skirting common issues

Here are some useful tips:

  • Embrace .prop(): While element.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: Setting disabled to false 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:

// All inputs be like: "Gone fishing" $('input[type="text"]').prop('disabled', true); // All inputs be like: "Open for business" $('input[type="text"]').prop('disabled', false);

This is quite convenient especially handling forms where unrelated inputs rely on certain conditions.