6

I know I can use something described here: How can I know which radio button 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?

3 Answers 3

8
var myRadio = jQuery("input[name=myradiogroup]");
var selectedRadio = myRadio.filter(":checked");
alert( selectedRadio.val() );
3
  • 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.
    – aw crud
    Commented Aug 24, 2010 at 16:24
  • 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
    Commented Aug 24, 2010 at 16:28
  • Whoops, should be filter. That is what I get for answering and eating at the same time. Altered the code. Commented Aug 24, 2010 at 16:42
4

Could do

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

Now you can check "myValue" anytime you wish.

Not the answer you're looking for? Browse other questions tagged or ask your own question.