tags:

views:

7905

answers:

2

How to set radio option checked onload with jQuery?

Need to check if no default is set and then set a default

+14  A: 

Say you had radio buttons like these, for example:

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

And you wanted to check the one with a value of "Male" onload if no radio is checked:

$(function() {
    var $radios = $('input:radio[name=gender]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=Male]').attr('checked', true);
    }
});
Paolo Bergantino
You ROCK!!! Saved me a headache, thanks :)
Phill Pafford
Just wondering Paolo, IIRC the spec says that the checked attribute is meant to be checked="checked" (though I may be wrong). Does jQuery translate true to 'checked' in this example? Just curious...
alex
My original example had 'checked','checked' , it's one of those things I can never remember which one is right. jQuery figures it out either way, but I know if you want to set the actual checked attribute of a DOM element it is supposed to be a boolean, like, document.getElementById('x').checked = true; - so I went with that.
Paolo Bergantino
Ah, thanks for getting back to me. Makes sense!
alex
Thanx a lot! Took me quite a while to find this.
tvgemert
+3  A: 

How about a one liner?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);
Andrew McCombe