how to set radio option checked onload with jQuery

JqueryRadio Button

Jquery Problem Overview


How to set radio option checked onload with jQuery?

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

Jquery Solutions


Solution 1 - Jquery

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);
        }
    });

Solution 2 - Jquery

How about a one liner?

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

Solution 3 - Jquery

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();

Solution 4 - Jquery

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

Solution 5 - Jquery

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);

Solution 6 - Jquery

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"]);
}

Solution 7 - Jquery

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

Solution 8 - Jquery

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);
};

Solution 9 - Jquery

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>

Solution 10 - Jquery

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.

Solution 11 - Jquery

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

Solution 12 - Jquery

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');

Solution 13 - Jquery

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.

Solution 14 - Jquery

//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.

Solution 15 - Jquery

This works for multiple radio buttons

$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhill PaffordView Question on Stackoverflow
Solution 1 - JqueryPaolo BergantinoView Answer on Stackoverflow
Solution 2 - JqueryAndrew McCombeView Answer on Stackoverflow
Solution 3 - JquerychaikoView Answer on Stackoverflow
Solution 4 - JqueryShital ShahView Answer on Stackoverflow
Solution 5 - Jqueryclayzermk1View Answer on Stackoverflow
Solution 6 - JquerySaramView Answer on Stackoverflow
Solution 7 - JqueryRazan PaulView Answer on Stackoverflow
Solution 8 - JqueryWildSpideeView Answer on Stackoverflow
Solution 9 - JqueryIftikharView Answer on Stackoverflow
Solution 10 - JqueryCarlos TorresView Answer on Stackoverflow
Solution 11 - Jqueryrookie to jqueryView Answer on Stackoverflow
Solution 12 - JquerykarmaView Answer on Stackoverflow
Solution 13 - JqueryBradley FloodView Answer on Stackoverflow
Solution 14 - JqueryJrBrionesView Answer on Stackoverflow
Solution 15 - JqueryHari LakkakulaView Answer on Stackoverflow