开发者

edge case for selecting a checked radio input with jquery

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 rath开发者_如何学Goer 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.


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()".


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 :)


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.

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

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

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜