how to set radio option checked onload with jQuery
Asked Answered
D

15

327

How to set radio option checked onload with jQuery?

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

Densimeter answered 15/5, 2009 at 22:7 Comment(1)
@ryenus wouldn't the other question be a duplicate of mine since I asked mine before the other question?Densimeter
B
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);
        }
    });
Bregenz answered 15/5, 2009 at 22:12 Comment(6)
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...Mantua
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.Bregenz
just want to add this square bracket notation [name=gender] doesn´t work in stock browser of windows phone 7.Smoothen
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 #4619233 (duplicate?)Belt
A quick one: DON'T use $radios.removeAttr('checked') before the prop. It will confuse the browser and the posted values.Huberty
Btw prop() requires jQuery v1.6+. For older versions see other answers.Candless
L
120

How about a one liner?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);
Lamarre answered 23/7, 2010 at 9:23 Comment(6)
The above is better as it supports more complex name values.Piercy
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.Macy
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: 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);Septilateral
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);Cavell
Correct - prop() is now the recommended method to access properties.Lamarre
Simpler: $('input:radio[name="gender"][value="Male"]').attr('checked', true);Rooftree
P
60

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();
Poundage answered 6/8, 2011 at 4:58 Comment(1)
i would recommend you use trigger('click') bit more readable and stops a method call.Defray
C
44

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

Colubrid answered 28/12, 2013 at 1:16 Comment(0)
D
24

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);
Demonetize answered 8/10, 2012 at 23:18 Comment(0)
C
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"]);
}
Calycine answered 24/4, 2013 at 12:31 Comment(5)
This is bad your scanning every element for a value i don't recommend this is used everDefray
@MartinBarker can you explain what do you men by 'scanning' ?Calycine
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 idDefray
@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.Calycine
To address the concerns above, use $("input[name=gender]") or $("input[name=gender]:radio") or (for modern browsers) $("input[name=gender][type=radio]")Alitaalitha
H
9

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
Hoof answered 15/6, 2016 at 0:57 Comment(1)
This solution worked for me. This should've been selected answer. Very clean method.Multivibrator
M
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);
};
Melvinamelvyn answered 8/11, 2012 at 19:32 Comment(0)
D
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');
Digestion answered 14/9, 2015 at 11:46 Comment(0)
S
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>
Sandisandidge answered 15/4, 2016 at 10:52 Comment(0)
T
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.

Theatre answered 12/11, 2010 at 12:59 Comment(1)
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 sayDensimeter
C
2
 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);
Carrasco answered 16/12, 2012 at 13:10 Comment(1)
Please don't post code-only answers. Please give an explanation too.Scrobiculate
W
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.

Wachter answered 13/11, 2013 at 23:23 Comment(0)
K
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.

Katlynkatmai answered 24/9, 2013 at 15:44 Comment(0)
S
0

This works for multiple radio buttons

$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);
Sinewy answered 6/2, 2019 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.