views:

61

answers:

3

Hi all! I have a problem selecting a checked radio button with jquery. The radio buttons are generated by a function from a MVC that i'd rather not change and its name is like id[number]. Simply put, I have to check if any of these buttons are checked:

<input type="radio" name="id[1]" value="1"/>

<input type="radio" name="id[1]" value="2"/>

The problem is that jQuery('input:radio[name=id[1]]:checked').val() will select some function from the jQuery library.

Any help will be much appreciated.

A: 

u don't need the id[1] to be put that way... all you need is id...

as each name="id" can be put multiple times on a radio type.

and it will return the value of the checked radio or NULL if none selected.

jQuery('input:radio[name=id]:checked').val(); or jQuery('input:radio[name="id"]:checked').val();

note: the " quotes on the second one if the first does not work

Edited: or better yet try and put the id[1] in quotes... as im unfamiliar with MVC so you end up with :

jQuery('input:radio[name="id[1]"]:checked').val();

Val
+2  A: 

Are you sure you put the parentheses after val? When I've seen "some function from the jQuery library" showing up as a result, it's generally because I put "val" instead of "val()".

JacobM
no words can adequately describe how ashamed i am for making such a mistake...thank you!
altvali
I've done it before myself (which is why I recognized the symptoms). There's something about val() that feels more like a property than a method, I guess.
JacobM
A: 

If you just need to see if any are checked, use .length like this:

if($(":radio[name='id[1]']:checked").length) {
   //1 is checked
}

.length is how many are matched, and 0 ~= false in javascript :)

Nick Craver