views:

11357

answers:

5

I have a colection of checkboxes with generated ids and for a reason, some have an extra attribute. Is possible using JQuery to check if an element has a specific attribut ? For example can I verify if the following element has as attribute "myattr" ? The value of the attribute can vary.

<input type="checkbox" id="A" myattr="val_attr">A</input>

Thank you for all the responses. For example how can I get a collection of all checkboxes that have this attribute without checking one by one ? Is possible ?

+10  A: 
if ($('#A').attr('myattr')) {
    // attribute exists
} else {
    // attribute does not exist
}

EDIT:

The above will fall into the else-branch when myattr exists but is an empty string or "0". If that's a problem you should explicitly test on undefined:

if ($('#A').attr('myattr') !== undefined) {
    // attribute exists
} else {
    // attribute does not exist
}
Stefan Gehrig
+7  A: 

Do you mean can you select them? If so, then yes:

$(":checkbox[myattr]")
cletus
yes, thank you. this was what I wanted
Ciprian Grosu
A: 
$("input#A").attr("myattr") == null
Malcolm Frexner
$().attr() will not return null as suggested by our example, instead it'll return undefined.
Stefan Gehrig
Works for me in firebug, but that may be an firebug thing
Malcolm Frexner
Haven't tried it, but that's what the documentation says: http://docs.jquery.com/Attributes/attr#name
Stefan Gehrig
+3  A: 

In JavaScript,...

null == undefined

...returns true*. It's the difference between == and ===. Also, the name undefined can be defined (it's not a keyword like null is) so you're better off checking some other way. The most reliable way is probably to compare the return value of the typeof operator.

typeof o == "undefined"

Nevertheless, comparing to null should work in this case.

* Assuming undefined is in fact undefined.

bamccaig