views:

41

answers:

3

I know I can use something described here: http://stackoverflow.com/questions/596351/how-can-i-get-which-radio-is-selected-via-jquery

i.e. jQuery("input[name=myradiogroup]:checked").val() to get the selected radio button value. But I'd like to cache the radio group and determine which value is selected at a later point in time.

I want to do something like:

var myRadio = jQuery("input[name=myradiogroup]");
//some code
var value = myRadio.getCheckedButton().val();

Any way to do this or do I have to explicitly run the selector with :checked in it every time I want to find out the selected value?

+2  A: 
var myRadio = jQuery("input[name=myradiogroup]");
var selectedRadio = myRadio.filter(":checked");
alert( selectedRadio.val() );
epascarello
Hmm, that's odd... I saw an answer like that in the linked question but I couldn't get it to work. I'll try again, but it seems like .find is searching for child elements, ignoring the radio group itself, so I always get an empty result.
RenderIn
`find` will only look in descendants, so it will return an empty set since the checkbox elements have no descendants and calling `val` on that empty set will return `undefined`
Anurag
Whoops, should be filter. That is what I get for answering and eating at the same time. Altered the code.
epascarello
Sample code: http://jsbin.com/ikuha/
epascarello
+1  A: 

Could do

myRadio.filter(':checked').val()
Anurag
A: 
myValue="";
$('input[name=myradiogroup]').change(function() {
     myValue= this.value;
    alert(myValue);
});

Now you can check "myValue" anytime you wish.

Mark Schultheiss