[jquery] how to set radio option checked onload with jQuery

How to set radio option checked onload with jQuery?

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

This question is related to jquery radio-button

The answer is


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


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

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.


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

How about a one liner?

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

De esta forma Jquery obtiene solo el elemento checked

$('input[name="radioInline"]:checked').val()

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>

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

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

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


This works for multiple radio buttons

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

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.


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

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

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