To properly disable an element, it is recommended to use .removeAttr('disabled')
instead of .attr('disabled', false)
. It is also advised to cache your jQuery selectors.
Edit: A suggestion after the fact is to clear the text in the field when disabling it, which can be achieved by adding .val('')
. If you wish to hide the field, you may also include .hide()
and .show()
in the respective cases.
I have created a demo on JSFiddle to showcase a functional implementation:
var $state = $('#state'), $province = $('#province');
$state.change(function () {
if ($state.val() == 'other') {
$province.removeAttr('disabled');
} else {
$province.attr('disabled', 'disabled').val('');
}
}).trigger('change'); // added trigger to calculate initial state
The .trigger('change')
method will simulate a change event, executing the function once during binding. This ensures that the #province
element will be disabled or enabled based on the selected state at the time of execution. Without this, the province field would remain accessible unless explicitly marked as disabled in the HTML code.