10

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

0

3 Answers 3

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/

2
  • The true parameter in prop('disabled') is redundant. It's not like the attr() function
    – SeanCannon
    Commented Aug 5, 2011 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 ;)
    – SeanCannon
    Commented Aug 5, 2011 at 19:58
8
$('#my_div').find('*').prop('disabled',true);

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

5
  • 1
    prop('disabled',true) as prop('disabled') just returns value Commented Aug 5, 2011 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: blog.jquery.com/2011/05/03/jquery-16-released
    – SeanCannon
    Commented Aug 5, 2011 at 19:57
  • 1
    What's with the find('*') over $('#my_div *')? And as mentioned by karim79, 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.
    – Mog
    Commented Aug 5, 2011 at 20:02
  • find('*') is more than twice as fast as $('#my_div *'). Here's some benchmarking evidence: jsperf.com/selector-specific-vs-find
    – SeanCannon
    Commented Aug 5, 2011 at 20:08
  • To re-enable use $('#my_div').find('*').prop('disabled',false);
    – Developer
    Commented Sep 20, 2016 at 15:11
6
$('div').find('input, a, button').prop('disabled', true);

or maybe all:

$('div *').prop('disabled', true);
1
  • 1
    -1 you should be using prop() instead of attr() for properties such as "disabled", "checked", "selected", etc.
    – SeanCannon
    Commented Aug 5, 2011 at 19:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.