Input elements can be easily disabled but what way is there to enable them?
The below code can disable but not enable the input element.
$('#dis').click(function() {
$('#inp').attr('disabled', 'true');
});
$('#enb').click(function() {
$('#inp').attr('disabled', 'false');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id='inp' type='text'>
<button id='enb'>Enable</button>
<button id='dis'>Disable</button>
The disable/enable an input element in jQuery can be done by using prop() method. The prop() method is used to set or return properties and values for the selected elements.
To remove disabled attribute using jQuery, use the removeAttr() method. You need to first remove the property using the prop() method. It will set the underlying Boolean value to false.
You can't disable anything with CSS, that's a functional-issue. CSS is meant for design-issues. You could give the impression of a textbox being disabled, by setting washed-out colors on it. Keep in mind that disabled inputs won't pass their values through when you post data back to the server.
Tip: Disabled <input> elements in a form will not be submitted!
The issue was with your code having true
and false
written in quotes, making them strings instead of booleans. Note that both 'true'
and 'false'
are truthy values, and thus your code set the enabled value to true in both cases.
I expect the following will work for you, check the snippet as well:
$('#dis').click(function() {
$("#inp").prop('disabled', true);
});
$('#enb').click(function() {
$("#inp").prop('disabled', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id='inp' type='text'>
<button id='enb'>Enable</button>
<button id='dis'>Disable</button>
Just to expand on the answer...
The real problem is that you are trying to set disabled to false via setAttribute()
which doesn't behave as you are expecting. An element is disabled if the disabled-attribute is set, regardless of value
so, disabled="true"
, disabled="disabled"
and disabled="false"
are all equivalent: the element gets disabled).
You should instead remove the complete attribute
$('#enb').click(function() {
$('#inp').removeAttr('disabled');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With