简体   繁体   中英

Using jQuery how can we remove disabled attribute from all elements whose value is false?

I have input checkboxes printed like the following.

<input type="checkbox" id="a1" value="11" disabled="false">
<input type="checkbox" id="a2" value="21" disabled="true">
<input type="checkbox" id="a3" value="31" disabled="false">

I know the disabled attribute takes no value. So when the attribute is present the element becomes disabled irrespective of the value assigned to it. I want to remove all the disabled attribute from all input elements whose value is false.

Using jQuery I would like to use code like the following.

$("*[disabled]").not(true).removeAttr("disabled");

Why don't you just match elements where disabled is false ?

$('[disabled="false"]​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​')​.removeAttr('disabled');​​​

Demo: http://jsfiddle.net/ASN29/

The presence of the disabled attribute automatically makes the element disabled, regardless of the attribute's value, so this isn't a very good idea. How does the HTML become this way?

You could simply use a selector like this:

$('input[disabled="false"]').removeAttr("disabled");

jsFiddle Demo

Instead of * , I added input , it narrows the query down a lot. This will search for input elements that have an attribute called disabled having the value false .

I would suggest you don't do this at all. That HTML should have never been generated.

If you want to enabled them use the .prop() instead .. ( that is because disabled as an actual property of checkbox inputs )

$('input[disabled="false"]').prop('disabled', false);

Demo at http://jsfiddle.net/gaby/Bn4dr/


The correct way, though, would be to print the proper html directly

<input type="checkbox" id="a1" value="11">
<input type="checkbox" id="a2" value="21" disabled>
<input type="checkbox" id="a3" value="31">
​$(document).ready(function (){
    $('input:disabled').removeAttr('disabled');    
});​

Here is the jsFiddle for it and documentation on :disabled selector

$('input[disabled="false"]').removeAttr("disabled");

See http://jsfiddle.net/JKs4C/

As to whether this is a good idea, on the other hand... I think the real answer is to fix up your server-side rendering to omit the disabled attribute entirely for elements that aren't disabled. Otherwise you'll end up with all elements disabled if your scripts go wrong, noscript, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM