326

How to set radio option checked onload with jQuery?

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

Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
Phill Pafford
  • 83,471
  • 91
  • 263
  • 383

15 Answers15

604

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]').prop('checked', true);
        }
    });
bruno
  • 2,213
  • 1
  • 19
  • 31
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 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 May 15 '09 at 22:36
  • 8
    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 May 15 '09 at 22:37
  • just want to add this square bracket notation [name=gender] doesn´t work in stock browser of windows phone 7. – 最白目 Feb 07 '13 at 07:28
  • 1
    I just tried it out with FF and jQuery 1.9.1 and .attr('checked', true); does not work, however .prop('checked', true); does. look at http://stackoverflow.com/questions/4618733/set-selected-radio-from-radio-group-with-a-value (duplicate?) – IARI Apr 13 '13 at 23:52
  • A quick one: DON'T use `$radios.removeAttr('checked')` before the prop. It will confuse the browser and the posted values. – igasparetto Oct 15 '14 at 12:08
  • Btw `prop()` requires jQuery v1.6+. For older versions see other answers. – Wtower Jan 13 '15 at 14:33
119

How about a one liner?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);
Andrew McCombe
  • 1,603
  • 1
  • 12
  • 13
  • The above is better as it supports more complex name values. – J. Martin Jul 03 '11 at 17:44
  • Thank you! This one worked and I didn't get the error like the first answer - $radios.filter(...).prop is not a function I did try putting in the extra quotes. I geuss it didn't like the props. – Michael K May 30 '13 at 22:39
  • 14
    This does not fully answer the ops question - it needs to check if a default option is already checked first. Also you should now use prop() instead of attr() for this kind of thing. For explanation, see the "Attributes vs. Properties" section here: http://api.jquery.com/prop/. Also there's no need for the extra filter, you can just combine the 2 selectors e.g. $("input[name=gender][value=Male]").prop("checked", true); – jackocnr Apr 02 '14 at 21:56
  • 4
    This solution works for the first time I set the radio but fails afterwards. By using "prop" instead of "attr", it works perfectly. So: $('input:radio[name="gender"]').filter('[value="Male"]').prop('checked', true); – Andrew Jan 19 '15 at 15:39
  • 2
    Correct - prop() is now the recommended method to access properties. – Andrew McCombe Feb 03 '15 at 11:49
  • 2
    Simpler: $('input:radio[name="gender"][value="Male"]').attr('checked', true); – Régis Jun 13 '17 at 13:14
57

This one will cause form.reset() failure:

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

But this one works:

$('input:radio[name=gender][value=Male]').click();
chaiko
  • 599
  • 4
  • 3
43

JQuery has actually two ways to set checked status for radio and checkboxes and it depends on whether you are using value attribute in HTML markup or not:

If they have value attribute:

$("[name=myRadio]").val(["myValue"]);

If they don't have value attribute:

$("#myRadio1").prop("checked", true);

More Details

In first case, we specify the entire radio group using name and tell JQuery to find radio to select using val function. The val function takes 1-element array and finds the radio with matching value, set its checked=true. Others with the same name would be deselected. If no radio with matching value found then all will be deselected. If there are multiple radios with same name and value then the last one would be selected and others would be deselected.

If you are not using value attribute for radio then you need to use unique ID to select particular radio in the group. In this case, you need to use prop function to set "checked" property. Many people don't use value attribute with checkboxes so #2 is more applicable for checkboxes then radios. Also note that as checkboxes don't form group when they have same name, you can do $("[name=myCheckBox").prop("checked", true); for checkboxes.

You can play with this code here: http://jsbin.com/OSULAtu/1/edit?html,output

Shital Shah
  • 63,284
  • 17
  • 238
  • 185
23

I liked the answer by @Amc. I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop() for the official best practices on the subject.

Consider the same input tags from @Paolo Bergantino's answer.

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

The updated one-liner might read something like:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);
clayzermk1
  • 1,018
  • 1
  • 12
  • 14
16

I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:

$("[name=gender]").val(["Male"]);

Note: Passing array is important.

Conditioned version:

if (!$("[name=gender]:checked").length) {
    $("[name=gender]").val(["Male"]);
}
Saram
  • 1,500
  • 1
  • 18
  • 35
  • 1
    This is bad your scanning every element for a value i don't recommend this is used ever – Barkermn01 Jan 14 '14 at 22:49
  • @MartinBarker can you explain what do you men by 'scanning' ? – Saram Jan 15 '14 at 07:51
  • Searching the DOM, if you use nothing but an attribute your forcing jQuery to go though every element in the DOM and check for that match same as if you were to use `$("*")` it would match everything so you should use a type at lease `$("input")` or an ID would be ideal as the DOM has native calls to get an element by id – Barkermn01 Jan 19 '14 at 15:24
  • @MartinBarker - I agree. Usually I prefix selector with form id or provide context param. Currently scanning DOM is not jQuery effort but internal browser engine, `document.querySelectorAll` makes all job. – Saram Jan 20 '14 at 15:23
  • To address the concerns above, use `$("input[name=gender]")` or `$("input[name=gender]:radio")` or (for modern browsers) `$("input[name=gender][type=radio]")` – David Balažic Jul 28 '16 at 13:21
8

Native JS solution:

 document.querySelector('input[name=gender][value=Female]').checked = true;

http://jsfiddle.net/jzQvH/75/

HTML:

<input type='radio' name='gender' value='Male'> Male
<input type='radio' name='gender' value='Female'>Female
Razan Paul
  • 13,618
  • 3
  • 69
  • 61
7

If you want it to be truly dynamic and select the radio that corresponds to the incoming data, this works. It's using the gender value of the data passed in or uses default.

if(data['gender'] == ''){
 $('input:radio[name="gender"][value="Male"]').prop('checked', true);
}else{
  $('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
};
WildSpidee
  • 71
  • 1
  • 1
3

Here is example with above methods:

<div class="ui-field-contain">
<fieldset data-role="controlgroup" data-type="horizontal">    <legend>Choose a pet:</legend>
    <input type="radio" name="radio-choice-2" id="radio-choice-1" value="choice1">
    <label for="radio-choice-1">Cat</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-2" value="choice2">
    <label for="radio-choice-2">Dog</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-3" value="choice3">
    <label for="radio-choice-3">Hamster</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-4" value="choice4">
    <label for="radio-choice-4">Lizard</label>
  </fieldset>
</div>

In javascript:

$("[name = 'radio-choice-2'][value='choice3']").prop('checked', true).checkboxradio('refresh');
karma
  • 903
  • 10
  • 26
3

And if you want to pass a value from your model and want to select a radio button from the group on load based on value, than use:

Jquery:

var priority = Model.Priority; //coming for razor model in this case
var allInputIds = "#slider-vertical-" + itemIndex + " fieldset input";

$(allInputIds).val([priority]); //Select at start up

And the html:

<div id="@("slider-vertical-"+Model.Id)">
 <fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("high-"+Model.Id)" value="1" checked="checked">
    <label for="@("high-"+Model.Id)" style="width:100px">@UIStrings.PriorityHighText</label>

    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("medium-"+Model.Id)" value="2">
    <label for="@("medium-"+Model.Id)" style="width:100px">@UIStrings.PriorityMediumText</label>

    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("low-"+Model.Id)" value="3">
    <label for="@("low-"+Model.Id)" style="width:100px">@UIStrings.PriorityLowText</label>
 </fieldset>
</div>
Iftikhar
  • 79
  • 1
  • 5
2
 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);
daniel__
  • 11,633
  • 15
  • 64
  • 91
2

Don't need all that. With simple and old HTML you can achieve what you want. If you let the radio you want checked by default like this:
<input type='radio' name='gender' checked='true' value='Male'>
When page loads, it'll come checked.

Adrian Pronk
  • 13,486
  • 7
  • 36
  • 60
  • 4
    yes but I need it to be dynamic as the referring site would pass in the defaults on page load. It's been a while since I thought about this question so I hope I'm understanding what you're trying to say – Phill Pafford Nov 12 '10 at 15:05
1

Note this behavior when getting radio input values:

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.

Bradley Flood
  • 10,233
  • 3
  • 46
  • 43
0

//If you are doing it on javascript or a framework like backbone, you will encounter this a lot you could have something like this

$MobileRadio = $( '#mobileUrlRadio' );

while

$MobileRadio.checked = true;

will not work,

$MobileRadio[0].checked = true;

will.

your selector can be as the other guys above recommended too.

JrBriones
  • 2,930
  • 1
  • 13
  • 5
0

This works for multiple radio buttons

$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);
Vega
  • 27,856
  • 27
  • 95
  • 103
Hari Lakkakula
  • 199
  • 1
  • 4