2393
$input.disabled = true;

or

$input.disabled = "disabled";

Which is the standard way? And, conversely, how do you enable a disabled input?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
omg
  • 123,990
  • 135
  • 275
  • 341
  • 6
    possible duplicate of [Remove disabled attribute using JQuery?](https://stackoverflow.com/questions/13626517/remove-disabled-attribute-using-jquery) – user2381114 Apr 29 '14 at 12:58
  • 1
    I found the [DependsOn](https://github.com/dstreet/dependsOn) plugin which you might find useful – Onshop Jul 04 '14 at 09:52

19 Answers19

3937

jQuery 1.6+

To change the disabled property you should use the .prop() function.

$("input").prop('disabled', true);
$("input").prop('disabled', false);

jQuery 1.5 and below

The .prop() function doesn't exist, but .attr() does similar:

Set the disabled attribute.

$("input").attr('disabled','disabled');

To enable again, the proper method is to use .removeAttr()

$("input").removeAttr('disabled');

In any version of jQuery

You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:

// assuming an event handler thus 'this'
this.disabled = true;

The advantage to using the .prop() or .attr() methods is that you can set the property for a bunch of selected items.


Note: In 1.6 there is a .removeProp() method that sounds a lot like removeAttr(), but it SHOULD NOT BE USED on native properties like 'disabled' Excerpt from the documentation:

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5

gnarf
  • 101,278
  • 24
  • 124
  • 158
  • 9
    As an aside, remember that, if you want to disable ALL form input controls - incl. checkboxes, radios, textareas, etc. - you have to select `':input'`, not just `'input'`. The latter selects only actual elements. – Cornel Masson Aug 16 '12 at 08:10
  • 35
    @CornelMasson `input,textarea,select,button` is a little better to use than `:input` -- `:input` as a selector is quite inefficient because it has to select `*` then loop over each element and filter by tagname - if you pass the 4 tagname selectors directly it is MUCH faster. Also, `:input` is not a standard CSS selector, so any performance gains that are possible from `querySelectorAll` are lost – gnarf Sep 16 '12 at 07:01
  • 3
    Does this just prevent the user from accessing it, or does it actually remove it from the web request? – OneChillDude May 02 '13 at 15:45
  • @bwheeler96 It does both. A disabled `input` element will not be submitted, and the user will be unable to change its value. – nullability Aug 20 '13 at 15:07
  • Also remember to use true/false booleans and not strings to enable/disable properties – dbrin May 08 '14 at 23:57
  • 4
    Using the `.removeProp("disabled")` was causing the issue of "property getting removed completely and not getting added again" as pointed out by @ThomasDavidBaker, in case of some browsers like Chrome, whereas it was working fine on some like Firefox. We should really be careful here. Always use `.prop("disabled",false)` instead – Sandeepan Nath Jun 25 '14 at 08:08
  • 6
    Neither .prop or .attr are sufficient for disabling anchor elements; .prop won't even grey out the 'control' (.attr does, but the href is still active). You have to also add a click event handler that calls preventDefault(). – Jeff Lowery Sep 25 '14 at 18:50
  • Since IE8 and below don't support the `:disabled` pseudo-class, you have to use the `[disabled=disabled]` selector to style disabled objects - which means you should follow geekbuntu's answer below if you care about cross-browser support. Basically, despite the large number of upvotes, this answer is incorrect and `attr` / `removeAttr` is the way to go. – Ola Tuvesson Nov 23 '14 at 14:17
  • @JeffLowery You are right. I have to use them both to disable an anchor element. – wings Nov 17 '16 at 02:35
  • 1
    var o=$("#elem");o.disabled=true; does not work here. It would be nice if it did, any thoughts? – Henrik Erlandsson Apr 06 '18 at 11:49
  • 1
    the funniest part of this answer is the use of single quotes and double quotes in the same line of JavaScript – quemeful Sep 26 '18 at 20:28
  • This ties in with slightly with the issue of toggling an input being enabled or disabled. If you use this in the inputs own .click event it will work to disable, but then the input element itself becomes unclickable after its disabled. Consider using this on a container for the input such as a div, span, or even an li if in a list style form. – Mike Jan 27 '19 at 19:19
  • what should be done for dynamically adding elements.?! – Jerry King May 07 '21 at 09:46
63

Just for the sake of new conventions && making it adaptable going forward (unless things change drastically with ECMA6(????):

$(document).on('event_name', '#your_id', function() {
    $(this).removeAttr('disabled');
});

and

$(document).off('event_name', '#your_id', function() {
    $(this).attr('disabled','disabled');   
});
geekbuntu
  • 811
  • 6
  • 4
  • 12
    Jikes! Why `$(document).on('event_name', '#your_id', function() {...})` instead of `$('#your_id').on('event_name', function() {...})`. As described in the [jQuery .on() documentation](http://api.jquery.com/on/) the former uses delegation and listens to _all_ `event_name` events that bubble up to `document` and checks them for a matching `#your_id`. The latter listens specifically to `$('#your_id')` events only and that scales better. – Peter V. Mørch Jul 31 '13 at 20:09
  • 25
    The former works for elements inserted into the DOM at any point, the latter only for those extant at that moment. – crazymykl Oct 10 '13 at 16:56
  • 1
    @crazymykl Correct but you shouldn't add elements with an id already present on your page. – SepehrM Apr 07 '16 at 13:46
36
    // Disable #x
    $( "#x" ).prop( "disabled", true );
    // Enable #x
    $( "#x" ).prop( "disabled", false );

Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled". For e.g.:

  //To disable 
  $('.someElement').attr('disabled', 'disabled');

To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:

//To enable 
$('.someElement').removeAttr('disabled');

// OR you can set attr to "" 
$('.someElement').attr('disabled', '');

refer :http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html

Harini Sekar
  • 630
  • 7
  • 14
15
$("input")[0].disabled = true;

or

$("input")[0].disabled = false;
Sajjad Shirazy
  • 1,999
  • 22
  • 22
9

You can put this somewhere global in your code:

$.prototype.enable = function () {
    $.each(this, function (index, el) {
        $(el).removeAttr('disabled');
    });
}

$.prototype.disable = function () {
    $.each(this, function (index, el) {
        $(el).attr('disabled', 'disabled');
    });
}

And then you can write stuff like:

$(".myInputs").enable();
$("#otherInput").disable();
Nicu Surdu
  • 7,326
  • 8
  • 63
  • 96
  • 3
    While wrapping the functionality is handy, you should have used `prop` and *not* `attr` with the `disabled` property for it to work correctly (assuming jQuery 1.6 or above). – Gone Coding May 20 '15 at 12:54
  • 1
    @TrueBlueAussie What is the downside of using `attr` ? I use the above code in some projects and as far as I remember it works ok – Nicu Surdu May 20 '15 at 14:56
  • 1
    The obvious exceptions are controls with properties behind the scenes. The most famous one is the `checked` property of checkboxes. Using `attr` will not give the same result. – Gone Coding May 20 '15 at 14:58
8

If you just want to invert the current state (like a toggle button behaviour):

$("input").prop('disabled', ! $("input").prop('disabled') );
daVe
  • 879
  • 2
  • 11
  • 18
  • 1
    thanks i have a same thing for the toggle it is; $("input").prop('disabled', function(i, v) { return !v; }); – Floww Apr 30 '20 at 09:31
5

There are many ways using them you can enable/disable any element :

Approach 1

$("#txtName").attr("disabled", true);

Approach 2

$("#txtName").attr("disabled", "disabled");

If you are using jQuery 1.7 or higher version then use prop(), instead of attr().

$("#txtName").prop("disabled", "disabled");

If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.

Approach 1

$("#txtName").attr("disabled", false);

Approach 2

$("#txtName").attr("disabled", "");

Approach 3

$("#txtName").removeAttr("disabled");

Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.

wild coder
  • 730
  • 1
  • 11
  • 17
2

Update for 2018:

Now there's no need for jQuery and it's been a while since document.querySelector or document.querySelectorAll (for multiple elements) do almost exactly same job as $, plus more explicit ones getElementById, getElementsByClassName, getElementsByTagName

Disabling one field of "input-checkbox" class

document.querySelector('.input-checkbox').disabled = true;

or multiple elements

document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
Pawel
  • 10,190
  • 4
  • 56
  • 60
  • 1
    the question specifically asks about jQuery...but equally your statement is correct, and worth knowing that jQuery doesn't _need_ to be used for this when there are multiple elements anymore. – ADyson Mar 01 '18 at 21:33
2

You can use the jQuery prop() method to disable or enable form element or control dynamically using jQuery. The prop() method require jQuery 1.6 and above.

Example:

<script type="text/javascript">
        $(document).ready(function(){
            $('form input[type="submit"]').prop("disabled", true);
            $(".agree").click(function(){
                if($(this).prop("checked") == true){
                    $('form input[type="submit"]').prop("disabled", false);
                }
                else if($(this).prop("checked") == false){
                    $('form input[type="submit"]').prop("disabled", true);
                }
            });
        });
    </script>
SPARTAN
  • 94
  • 4
2

this works for me

$("#values:input").attr("disabled",true);
$("#values:input").attr("disabled",false);
Siddhartha
  • 91
  • 1
  • 3
1

Disable true for input type :

In case of a specific input type (Ex. Text type input)

$("input[type=text]").attr('disabled', true);

For all type of input type

$("input").attr('disabled', true);
Hasib Kamal
  • 1,971
  • 20
  • 26
1

Disable:

$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.

Enable:

$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.
Tomer Ben David
  • 6,005
  • 1
  • 38
  • 20
1

Use like this,

 $( "#id" ).prop( "disabled", true );

 $( "#id" ).prop( "disabled", false );
smonff
  • 3,170
  • 2
  • 35
  • 44
Abdus Salam Azad
  • 3,109
  • 31
  • 23
0
<html>
<body>

Name: <input type="text" id="myText">



<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>

<script>
function disable() {
    document.getElementById("myText").disabled = true;
}
function enable() {
    document.getElementById("myText").disabled = false;
}
</script>

</body>
</html>
  • 1
    **From review queue**: May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT May 11 '17 at 01:41
0

I used @gnarf answer and added it as function

   $.fn.disabled = function (isDisabled) {
     if (isDisabled) {
       this.attr('disabled', 'disabled');
     } else {
       this.removeAttr('disabled');
     }
   };

Then use like this

$('#myElement').disable(true);
Imants Volkovs
  • 842
  • 11
  • 19
0

2018, without JQuery (ES6)

Disable all input:

[...document.querySelectorAll('input')].map(e => e.disabled = true);

Disable input with id="my-input"

document.getElementById('my-input').disabled = true;

The question is with JQuery, it's just FYI.

rap-2-h
  • 23,287
  • 23
  • 130
  • 217
0

Approach 4 (this is extension of wild coder answer)

txtName.disabled=1     // 0 for enable
<input id="txtName">
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
0

An alternate way to disable the input field is by using jQuery and css like this:

jQuery("#inputFieldId").css({"pointer-events":"none"})

and to enable the same input the code is as follows:

jQuery("#inputFieldId").css({"pointer-events":""})
mukhtar alam
  • 121
  • 10
-1

In jQuery Mobile:

For disable

$('#someselectElement').selectmenu().selectmenu('disable').selectmenu('refresh', true);
$('#someTextElement').textinput().textinput('disable');

For enable

$('#someselectElement').selectmenu().selectmenu('enable').selectmenu('refresh', true);
$('#someTextElement').textinput('enable');
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Atif Hussain
  • 821
  • 10
  • 19