Disable or enable an input field with jQuery

For jQuery 1.6 or above there is prop() function and lower jQuery versions have attr() function which can be used to disable or enable an input field. Further more DOM object’s disabled property also works with any version of jQuery to disable or enable an input field.

Single Input

If you are dealing with just an element then relying on the actual DOM object is bit faster than other methods which I will mention below.

jQuery 1.6+ using prop()

jQuery 1.5 and below using attr()

Points worth mentioning

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

In 1.6 there is a removeProp() method that sounds like removeAttr() but never use it on native properties like ‘disabled‘ as per jQuery documentation says:

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.

If you want to let disable/enable work for elements inserted into the DOM at any point then you should replace

$('#your_id').on('event_name', function() {...})

with

$(document).on('event_name', '#your_id', function() {...})

because the former is only for those extant at that moment.

You Might Interested In

1 COMMENT

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.