jQuery: checked value from variable name or $(this)

helgatheviking picture helgatheviking · Jan 31, 2011 · Viewed 7.2k times · Source

If I have some radio buttons:

<input type="radio" name="test" value="apple"> Apple<br/>
<input type="radio" name="test" value="banana" CHECKED> Banana<br/>
<input type="radio" name="test" value="carrot"> Carrot<br/>

and I then define the radio group in jQuery with

var test = $('input:radio[name="test"]')


How can I get the value of the checked element based on the variable test without re-writing

var test_val = $('input:radio[name="test"]:checked').val();

I've tried both

$(test):checked.val();
test:checked.val();

And as part of a change function I've also tried this:

$(test).change(function() {
    if ($(this):checked.val() == 'no') {
        $('#featured').stop().fadeOut();
    } else if ($(this):checked.val() == 'yes') {
        $('#featured').stop().fadeIn();
    }
});

Just wondering if this is possible or if I have to re-write out the full input selector to get the value.

P.S.
If IE8 doesn't support the :checked selector, what can I use instead?

Answer

jAndy picture jAndy · Jan 31, 2011

You can use .filter()help:

test.filter('input:checked')

.filter() does also support a callback:

test.filter(function() {
    return this.name === 'test' && this.checked
});

I wasn't aware that the :checked selector does not work with IE8. If that is true, the latter example should work (accessing the node expando directly)