问题
I have 2 <fieldset>
s on my page, but one of them should have all of it elements disabled depending on some user's choice.
The fieldsets contain text inputs, selects, and links. Is there a way to disable all of them instead of disabling them one by one?
回答1:
What about using the children selector?
$("#myfieldeset").children().attr("disabled", "disabled");
You can also filter the children selection:
$("#myfieldeset").children("a,input");
回答2:
You can set the disabled
attribute of fieldset
.
From MDN:
If this Boolean attribute is set, the form controls that are its descendants, except descendants of its first optional element, are disabled, i.e., not editable. They won't receive any browsing events, like mouse clicks or focus-related ones. Often browsers display such controls as gray.
HTML: <fieldset disabled> ... </fieldset>
JQuery: $('#myfieldset').prop('disabled', true);
JS: document.getElementById('#myFieldset').disabled = true;
Important note: This does not work properly on Internet Explorer due to a couple bugs, but works well just about everywhere else (including Edge).
IE Bugs: 1, 2
tl;dr: Text and File inputs don't properly disable, and the user can still interact with them
If this is a deal breaker, you need to go into the fieldset and put disabled
on its descendants as described in other answers here.
Browser support info: http://caniuse.com/#feat=fieldset-disabled
回答3:
Assuming you set a class="disableMe" on the fieldset you want to disable any input elements then the following code should do what you need:
$('fieldset.disableMe :input').attr('disabled', true)
回答4:
Why don't you just use:
$("#myfieldeset").attr("disabled", "disabled");
It worked for me. It disabled nicely all the children inputs.
EDIT: note thas the disabled attribute can be applied to fieldset element only in HTML5 (see merryprankster comment). Strangely enough, it does work with other browser than just Firefox and Opera, such as Chrome and Internet Explorer (tested IE7 and IE8).
回答5:
In addition to what others posted:
Use .prop()
instead of .attr()
:
$('#myfieldset').prop('disabled',true)
It is more correct with regard to the DOM.
And it does not seem to work well with validation. Both firefox and chrome won't let me submit the form With unfilled 'required' inputs in the disabled fieldset, but don't give any instructions on how to complete the form either.
回答6:
If for some reason you can't add an ID to the fieldset (which is usually preferred), you can always do this to hide all it's children elements:
$('fieldset:first > *').attr('disabled','disabled');
来源:https://stackoverflow.com/questions/781584/how-can-i-disable-all-elements-inside-a-fieldset-in-jquery