views:

58

answers:

4

I have 2 radios:

<input id="a_15_0" type="radio" value="abc" name="a_15"/>
<input id="a_15_1" type="radio" value="xyz" name="a_15"/>

Both are unselected. I have only the name of the radio, i.e a_15, but not the IDs.

1) How can I get the value of the selected option of this radio? E.g if the user clicked 'xyz', how can I get it? Right now I'm using:

var val=$('[name="a_15"]').val();

Which always gives abc even when xyz is selected.

2) How can I get xyz to be selected through javascript, without knowing the ID of the radio which says xyz? Doing:

$('[name="a_15"]').val('xyz');

Changes the value of both radios to xyz rather than selecting the one whose value had been xyz.

Do I need to use document.myForm.a_15.value? Would that work consistently?

+1  A: 

There are many ways of selectors in jQuery; id, class, etc..I believe this will do the job, not tested:

var val= $("input[name=a_15]:checked").val();

if you know the name of the form then this will definitely do it

var val= jQuery('#radio_form input:radio:checked').val();
TStamper
+2  A: 

1) try

var val = $('input[name=a_15]:checked').val();

jQuery docs on checked pseudo-class

2) the only solution I found is

$('input[name=a_15][value=xyz]').get(0).checked=true
Rafael
+1  A: 

Have you tried using the val() in conjunction with the :checked selector?

$('[name="a_15"]:checked').val();

As for setting the selection based on the value, you may have to perform a multiple attribute tests?

$('[name="a_15"][value="xyz"]').get(0).checked = true;
bendewey
I think it'll be a lot easier to use document.myForm.myRadio approach. Do you know if that would work both for getting the selected value of the radio and for selecting the value I want?
Click Upvote
I'm not a fan of mixing jquery selectors and the old fashion DOM selectors. If you app uses jquery then I would stick with this jQuery approach. But that's my opinion.
bendewey
Yes, and document.myForm didn't work anyways. Thanks a lot man, you're a life saver.
Click Upvote
The document.myForm approach has always given me browser compatability complications.
bendewey
A: 

you have the correct code here:

to run

to edit

the correct form is:

$("input[name='a_15']:checked").val();

as you can test using the links above

balexandre