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() );
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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
Whoops, should be filter. That is what I get for answering and eating at the same time. Altered the code.
4

Could do

myRadio.filter(':checked').val()

Comments

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

Now you can check "myValue" anytime you wish.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.