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.
1 2 | // assuming an event handler thus 'this' this.disabled = true; |
jQuery 1.6+ using prop()
1 2 3 4 | $('#your_id').on('event_name', function() { $("input").prop('disabled', true); //Disable input $("input").prop('disabled', false); //Enable input }) |
jQuery 1.5 and below using attr()
1 2 3 4 | $('#your_id').on('event_name', function() { $("input").attr('disabled','disabled'); //Disable input $("input").removeAttr('disabled'); //Enable input }) |
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.
Using jQuery prop() method you can enable or disable a form element. From jQuery 1.6+ you can use jQuery prop() method.
Disable a Control: $( “#elementID” ).prop( “disabled”, true );
Enable a Control: $( “#elementID” ).prop( “disabled”, false );
Read More: http://www.namasteui.com/enable-or-disable-an-input-field/