Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to enable disabled input [duplicate]

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>
like image 344
dorado Avatar asked Sep 26 '15 10:09

dorado


People also ask

How do I enable disabled input?

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.

How do I remove input field Disabled?

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.

How do I make input disabled in CSS?

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.

Do disabled inputs get submitted?

Tip: Disabled <input> elements in a form will not be submitted!


2 Answers

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>
like image 116
Selfish Avatar answered Sep 28 '22 12:09

Selfish


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');
});
like image 40
Alex Avatar answered Sep 28 '22 11:09

Alex