Interview Questions

How do I disable/enable a form element?

jQuery Interview Questions and Answers


(Continued from previous question...)

How do I disable/enable a form element?

There are two ways to disable/enable form elements.

Set the 'disabled' attribute to true or false:

// Disable #x
$('#x').attr('disabled', true);
// Enable #x
$('#x').attr('disabled', false);

Add or remove the 'disabled' attribute:
// Disable #x
$("#x").attr('disabled', 'disabled');
// Enable #x
$("#x").removeAttr('disabled');


You can try an example of enabling/disabling with the following demo:

and here's the source code to the demo:
<select id="x" style="width:200px;">
<option>one</option>
<option>two</option>
</select>
<input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
<input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>

(Continued on next question...)

Other Interview Questions