Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery RadioButton index

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

like image 320
Tomas Avatar asked Mar 19 '10 07:03

Tomas


1 Answers

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

like image 67
jitter Avatar answered Nov 03 '22 14:11

jitter