views:

2729

answers:

4

I'm trying to get the name of a class that matched a regex of a checked input.

If I have this:

 <input type="radio" class="toggle toggle-1" />
 <input type="radio" class="toggle toggle-2" checked="checked" />
 <input type="radio" class="toggle toggle-3" />

I want to find out that 'toggle-2' is the checked class.

 $('.toggle:checked').className.match(/toggle\-.+?\b/);

But that produced 'className is undefined' errors.

I think my problem is that I'm using className against a jQuery object. But I'm not really sure what the alternative is.

A: 

Don't you need an Id on all items jQuery is to look at?

Martin
No, jQuery can select elements based on pretty much any attribute using a wide variety of selectors.
Annabelle
Not at all. You can use any CSS selector (in addition to tons of other options) to locate elements in the DOM with jQuery.
Mark Hurd
@Martin: No. http://docs.jquery.com/Selectors
BenTheDesigner
+6  A: 

You can call the attr method to get any underlying attributes on the element you need.

$('.toggle:checked').attr('class').match(/toggle\-.+?\b/);
Shawn Simon
aha! Thanks, Shawn!
DA
A: 
$('.toggle:checked').hasClass('toggle-2');
Corey Hart
That doesn't answer the question, he's looking to get "toggle-2" as an answer
Sander Rijken
+2  A: 

className is a standard DOM member, not a jQuery wrapper property. Either access through $('something')[0].className or jQuery $('something').attr('class'), but you can't mix them.

You appear to have multiple radio​s without a shared name? That won't work, they'll all act ast separately checkable fields. All radio controls that belong together need to have the same name (but different value​s) and be placed within the same form.

bobince
Nice explanation, bobince. Thanks! As for the markup, it was just for example. I omitted a bunch of attributes.
DA