views:

360

answers:

1

Hello

How to get checked RadioButton Index using jQuery? I need to read it and save to cookies to load status later using code

$('input[name="compression"]')[{Reading from cookies code}].checked = true;



1<input name="compression" type="radio" value="1" checked="checked" />
2<input name="compression" type="radio" value="2" />
3<input name="compression" type="radio" value="3" />

Regards Tomas

+3  A: 

This returns the zero-based index of the selected radiobutton

$('input[name=compression]:checked').index()

For the case described in the comment use (which generally is the right syntax to use)

$('input[name=porient]:checked').index('input[name=porient]')

If you want to know why the first one gives wrong results you should read the .index() documentation

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

In the sample from the question there weren't any "other" siblings but your radiobuttons. Thus it works.

In the sample from the comment the <br /> tag is a sibling of the radiobuttons and thus is on index 1. That's why you think index() gives the wrong position

jitter
Strange thing, it works fine on "compression" radio buttons which code listed above, but on code below for "porient" radio buttons it return wrong indexes. If first radio button selected, it return 0 (ok) it second selected it return 2(!!!!) Can't understand what is going on. Any ideas? <p> <input name="porient" type="radio" value="portrait" checked="checked" />Portrait <br /> <input name="porient" type="radio" value="landscape" />Landscape </p>
Tomas
Check expanded answer
jitter