Explain Codes LogoExplain Codes Logo

Find if a textbox is disabled or not using jquery

javascript
jquery
javascript-8
event-handlers
Nikita BarsukovbyNikita Barsukov·Nov 25, 2024
TLDR

To verify if a textbox is disabled, use the jQuery function .is(':disabled') which returns a booleantrue if disabled, and false if not.

var isDisabled = $('#textboxId').is(':disabled');

Inspecting with .prop() method

The .prop('disabled') retrieves a boolean value of the disabled state of a textbox. It directly inspects the property of DOM elements, providing a more reliable reading especially for boolean values:

var isDisabled = $('#textboxId').prop('disabled'); // More reliable than asking a magic 8-ball

Addressing dynamic changes

That's super, however, if the disabled status of the textbox is toggled dynamically, you need to ensure the function call is executed at the right time, typically within an event handler or right after a DOM manipulation operation:

$('#someButton').click(function() { var isDisabled = $('#textboxId').prop('disabled'); // Like checking the oven right after you turn it off });

.prop() or .attr(), that's the question

.prop() generally provides a more accurate reading of boolean properties than .attr(), because it reflects the current state while .attr() shows the initial value from HTML. So, if accuracy is your game, .prop() is your dame.

var isReallyDisabled = $('#textboxId').prop('disabled'); // No more guessing games

Alternative checks and broader contexts

Select all disabled elements

If you're feeling more ambitious and wish to select all disabled elements on the page, jQuery stays one step ahead with $("selector:disabled"):

var allDisabled = $(":disabled"); // Catch 'em all, Pokémon!

Ensuring legacy support and syncing attribute with property

When dealing with legacy systems or code that switches between properties and attributes, you need to ensure both are synced:

$('#textboxId').prop('disabled', true).attr('disabled', 'disabled'); // A bit like saying “I do” and wearing the wedding ring

Conditional logic based on disabled state

Need to perform actions based on the textbox state? No worries, apply conditional logic like this:

if ($('#textboxId').prop('disabled')) { // Actions for when textbox is disabled } else { // Actions for when textbox is enabled }

Looking up individual textboxes

When handling multiple textboxes, you can still check a specific one with .is(':disabled'), with its unique ID or class:

$('#textBoxSpecific').is(':disabled'); // Like asking, "Are you sure you're not busy?" to that one textbox