10

How to make quick disabling/enabling of all the elements in any div (inputs, links and jQ Buttons)?

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153

3 Answers3

16

Links do not have a "disabled" property, so you'll have to work a bit harder.

$('#my_div').find(':input').prop('disabled', true);
$('#my_div a').click(function(e) {
    e.preventDefault();
});

To re-activate:

$('#my_div').find(':input').prop('disabled', false);
$('#my_div a').unbind("click");

The :input selector Selects all input, textarea, select and button elements.

Also see http://api.jquery.com/event.preventDefault/

karim79
  • 339,989
  • 67
  • 413
  • 406
  • The true parameter in `prop('disabled')` is redundant. It's not like the `attr()` function – AlienWebguy Aug 05 '11 at 19:46
  • FYI I just learned a few minutes ago the 'disabled' property does not set as expected with simply `prop('disabled')` whereas checked and selected do. `prop('disabled')` should set the property per their documentation. I smell a 1.6.3 bug fix ;) – AlienWebguy Aug 05 '11 at 19:58
8
$('#my_div').find('*').prop('disabled',true);

To re-enable, simply use .removeProp() http://api.jquery.com/removeProp/

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • 1
    prop('disabled',true) as prop('disabled') just returns value – Jacek Kaniuk Aug 05 '11 at 19:54
  • @jacek - good eye. this is a jquery bug, as it behaves as expected with other properties. As you can see in their 1.6 changelog, the expected behavior is to set the property not return the value: http://blog.jquery.com/2011/05/03/jquery-16-released/ – AlienWebguy Aug 05 '11 at 19:57
  • 1
    What's with the `find('*')` over `$('#my_div *')`? And as mentioned by [karim79](http://stackoverflow.com/questions/6961678/disable-enable-all-elements-in-div/6961782#6961782), links are unaffected by the `disabled` attribute, perhaps a flaw in the semantics of OPs question, or perhaps a misunderstanding of what `disabled` is used for. – Wesley Murch Aug 05 '11 at 20:02
  • `find('*')` is more than **twice as fast** as `$('#my_div *')`. Here's some benchmarking evidence: http://jsperf.com/selector-specific-vs-find – AlienWebguy Aug 05 '11 at 20:08
  • To re-enable use $('#my_div').find('*').prop('disabled',false); – Developer Sep 20 '16 at 15:11
6
$('div').find('input, a, button').prop('disabled', true);

or maybe all:

$('div *').prop('disabled', true);
Jacek Kaniuk
  • 5,229
  • 26
  • 28
  • 1
    -1 you should be using `prop()` instead of `attr()` for properties such as "disabled", "checked", "selected", etc. – AlienWebguy Aug 05 '11 at 19:41