10

How to properly enable/disable input field on click with jQuery?

I was experimenting with:

$("#FullName").removeAttr('disabled');

which removes disabled="disabled" from this input field:

<input id="FullName" style="width: 299px" value="Marko" disabled="disabled" />

But how to add it again with click on another button or how to disable input field on click?

gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
Drazek
  • 321
  • 2
  • 7
  • 16

7 Answers7

24

For jQuery version 1.6+ use prop:

$('#elementId').click(function(){
        $('#FullName').prop('disabled', true\false);
});

For older versions of jQuery use attr:

$('#elementId').click(function(){
        $('#FullName').attr('disabled', 'disabled'\'');
});
gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
5
$("#FullName").prop('disabled', true);

Will do.

But keep in mind after you disable it (by the above code) onclick handler wont work as its disabled. To enable it again add $("#FullName").removeAttr('disabled'); in the onclick handler of another button or field.

Shiplu Mokaddim
  • 52,462
  • 12
  • 127
  • 180
  • Thank you for making the second part clear. I could not figure out why the click event was not firing when the text input was disabled. – decapo Feb 14 '17 at 14:05
4
$('#checkbox-id').click(function()
{
    //If checkbox is checked then disable or enable input
    if ($(this).is(':checked'))
    {
        $("#to-enable-input").removeAttr("disabled"); 
        $("#to-disable-input").attr("disabled","disabled");
    }
    //If checkbox is unchecked then disable or enable input
    else
    {
        $("#to-enable-input").removeAttr("disabled"); 
        $("#to-disable-input").attr("disabled","disabled");
    }
});
songokuhd
  • 165
  • 1
  • 1
2

another simple method to enable/disable input feild

$("#anOtherButton").click(function() {
  $("#FullName").attr('disabled', !$("#FullName").attr('disabled'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<input id="FullName" style="width: 299px" value="Marko" disabled="disabled" />
<br>
<br>
<input type="button" id="anOtherButton" value="disable/enable" />
Rejeesh Prarath
  • 499
  • 5
  • 8
1

This should do it.

$("#FullName").attr('disabled', 'disabled');

Shiplu is correct, but use this if you have are not using jquery 1.6+

Brian S
  • 961
  • 7
  • 10
1
$("#anOtherButton").click(function(){
  $("#FullName").attr('disabled', 'disabled'); 
 });

sll
  • 56,967
  • 21
  • 100
  • 149
0

To toggle a field between disabled and enabled, try this:

$('#toggle_button').click(function () {
    $('#FullName').prop("disabled",

    function (i, val) {
        return !val;
    });
})
David Hempy
  • 3,210
  • 2
  • 28
  • 51