1022

I try to check a radio button with jQuery. Here's my code:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

And the JavaScript:

jQuery("#radio_1").attr('checked', true);

Doesn't work:

jQuery("input[value='1']").attr('checked', true);

Doesn't work:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

Doesn't work:

Do you have another idea? What am I missing?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Alexis
  • 16,629
  • 17
  • 62
  • 107
  • 1
    Thanks for your responses! I found the problem. Actually, the two first ways to do it are working. The point is I used jqueryUI to transform a set of 3 radio buttons into a button set with this code : jQuery("#type").buttonset(); but making this change before checking the radio was breaking the radio set (don't know why). Finally, I put the buttonset call after checking the radio and it works impeccably. – Alexis Apr 14 '11 at 18:43

33 Answers33

1674

For versions of jQuery equal or above (>=) 1.6, use:

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

For versions prior to (<) 1.6, use:

$("#radio_1").attr('checked', 'checked');

Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.

ADTC
  • 8,999
  • 5
  • 68
  • 93
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
  • 84
    In jQuery 1.9 or higher this solution won't work. Use $("#radio_1").prop("checked", true); instead. – installero Mar 15 '13 at 18:48
  • 44
    It helpful to add `.change()` to the end to trigger any other events on the page. – Foxinni Sep 17 '13 at 10:44
  • 34
    If you want the other radio buttons in the radio group to update properly use `$("#radio_1").prop("checked", true).trigger("click");` – Paul LeBeau Mar 29 '16 at 13:52
298

Try this.

In this example, I'm targeting it with its input name and value

$("input[name=background][value='some value']").prop("checked",true);

Good to know: in case of multi-word value, it will work because of apostrophes, too.

Vladimir Djuricic
  • 4,323
  • 1
  • 21
  • 22
  • For some reason this one worked for me for one troublesome radio group when just using the ID didn't work. – Michael K Apr 14 '22 at 18:46
  • @MichaelK maybe there's another element that has same id and it is not an input type? – Vladimir Djuricic Apr 15 '22 at 19:08
  • I looked for that, but there is nothing else with the same id. It is strange. I notice in the source I have "checked" for the originally checked radio button. But in the inspector I see it is checked="" so I wonder if that difference means anything. – Michael K Apr 19 '22 at 16:58
100

Short and easy to read option:

$("#radio_1").is(":checked")

It returns true or false, so you can use it in "if" statement.

TeaCupApp
  • 11,316
  • 18
  • 70
  • 150
Petr Lazarev
  • 3,102
  • 1
  • 21
  • 20
  • 7
    Thanks! This is what I was looking for, but (FYI) the OP was asking how to SET the radio button, not get the value. (The word "check" made the question confusing.) – Bampfer May 14 '15 at 21:54
98

One more function prop() that is added in jQuery 1.6, that serves the same purpose.

$("#radio_1").prop("checked", true); 
Umesh Patil
  • 10,475
  • 16
  • 52
  • 80
  • 15
    the `attr('checked', true)` stopped working for me with jQuery 1.9, this is the solution! – Pascal Feb 26 '13 at 15:40
36

Try this.

To check Radio button using Value use this.

$('input[name=type][value=2]').attr('checked', true); 

Or

$('input[name=type][value=2]').attr('checked', 'checked');

Or

$('input[name=type][value=2]').prop('checked', 'checked');

To check Radio button using ID use this.

$('#radio_1').attr('checked','checked');

Or

$('#radio_1').prop('checked','checked');
Lakshmana Kumar
  • 1,199
  • 3
  • 16
  • 34
23

Use prop() mehtod

enter image description here

Source Link

<p>
    <h5>Radio Selection</h5>

    <label>
        <input type="radio" name="myRadio" value="1"> Option 1
    </label>
    <label>
        <input type="radio" name="myRadio" value="2"> Option 2
    </label>
    <label>
        <input type="radio" name="myRadio" value="3"> Option 3
    </label>
</p>

<p>
    <button>Check Radio Option 2</button>
</p>


<script>
    $(function () {

        $("button").click(function () {
            $("input:radio[value='2']").prop('checked',true);
        });

    });
</script>
Code Spy
  • 9,626
  • 4
  • 66
  • 46
17

The $.prop way is better:

$(document).ready(function () {                            
    $("#radio_1").prop('checked', true);        
});

and you can test it like the following:

$(document).ready(function () {                            
    $("#radio_1, #radio_2", "#radio_3").change(function () {
        if ($("#radio_1").is(":checked")) {
            $('#div1').show();
        }
        else if ($("#radio_2").is(":checked")) {
            $('#div2').show();
        }
        else 
            $('#div3').show();
    });        
});
Amin Saqi
  • 18,549
  • 7
  • 50
  • 70
17

Try This:

$("input[name=type]").val(['1']);

http://jsfiddle.net/nwo706xw/

user4457035
  • 171
  • 1
  • 2
16

Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments. Make sure you invoke .change(), otherwise all the "on change" bindings will ignore this event.

$("#radio_1").prop("checked", true).change();
apatsekin
  • 1,524
  • 10
  • 12
9

You have to do

jQuery("#radio_1").attr('checked', 'checked');

That's the HTML attribute

JohnP
  • 49,507
  • 13
  • 108
  • 140
8

This answer is thanks to Paul LeBeau in a comment. I thought I'd write it up as a proper answer since there surprisingly wasn't one.

The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:

$(".js-my-radio-button").trigger("click");

This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change on the radio button.

Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.

Henrik N
  • 15,786
  • 5
  • 82
  • 131
7

If property name does not work don't forget that id still exists. This answer is for people who wants to target the id here how you do.

$('input[id=element_id][value=element_value]').prop("checked",true);

Because property name does not work for me. Make sure you don't surround id and name with double/single quotations.

Cheers!

Anjana Silva
  • 8,353
  • 4
  • 51
  • 54
7

Try this

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == '1')
        {
          // do something
        }
        else if($(this).val() == '2')
        {
          // do something
        }
        else if($(this).val() == '3')
        {
          // do something
        }
    });
});
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Jordan Jelinek
  • 136
  • 2
  • 9
7

We should want to tell it is a radio button.So please try with following code.

$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);
UWU_SANDUN
  • 1,123
  • 13
  • 19
7

Yes, it worked for me like a way:

$("#radio_1").attr('checked', 'checked');
Anjan Kant
  • 4,090
  • 41
  • 39
6
$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});
Eray
  • 79
  • 1
  • 1
6

Get value:

$("[name='type'][checked]").attr("value");

Set value:

$(this).attr({"checked":true}).prop({"checked":true});

Radio Button click add attr checked:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});
Naim Serin
  • 71
  • 1
  • 3
6

Try this with example

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>


<script>
$(document).ready(function () {
    $('#myForm').on('click', function () {
        var value = $("[name=radio]:checked").val();

        alert(value);
    })
});
</script>
saroj
  • 155
  • 2
  • 4
6

Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:

$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set
Colin R. Turner
  • 1,323
  • 15
  • 24
5

I use this code:

I'm sorry for English.

var $j = jQuery.noConflict();

$j(function() {
    // add handler
    $j('#radio-1, #radio-2').click(function(){

        // find all checked and cancel checked
        $j('input:radio:checked').prop('checked', false);

        // this radio add cheked
        $j(this).prop('checked', true);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="section">
  <legend>Radio buttons</legend>
  <label>
    <input type="radio" id="radio-1" checked>
    Option one is this and that&mdash;be sure to include why it's great
  </label>
  <br>
  <label>
    <input type="radio" id="radio-2">
    Option two can be something else
  </label>
</fieldset>
Community
  • 1
  • 1
deeplogger
  • 71
  • 1
  • 3
4

Try this

var isChecked = $("#radio_1")[0].checked;
Nazik
  • 8,696
  • 27
  • 77
  • 123
4

I've just have a similar problem, a simple solution is to just use:

.click()

Any other solution will work if you refresh radio after calling function.

spenibus
  • 4,339
  • 11
  • 26
  • 35
espace
  • 49
  • 2
4
function rbcitiSelction(e) {
     debugger
    $('#trpersonalemail').hide();
    $('#trcitiemail').show();
}

function rbpersSelction(e) {
    var personalEmail = $(e).val();
    $('#trpersonalemail').show();
    $('#trcitiemail').hide();
}

$(function() {  
    $("#citiEmail").prop("checked", true)
});
Seth
  • 10,198
  • 10
  • 45
  • 68
4

In addition, you can check if the element is checked or not:

if ($('.myCheckbox').attr('checked'))
{
   //do others stuff
}
else
{
   //do others stuff
}

You can checked for unchecked element:

$('.myCheckbox').attr('checked',true) //Standards way

You can also uncheck this way:

$('.myCheckbox').removeAttr('checked')

You can checked for radio button:

For versions of jQuery equal or above (>=) 1.6, use:

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

For versions prior to (<) 1.6, use:

$("#radio_1").attr('checked', 'checked');
Majedur
  • 3,074
  • 1
  • 30
  • 43
3

I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.

Example is in here:

$(function () {
    $('#CostAnalysis input[type=radio]').click(function () {
        var value = $(this).val();

        if (value == "Supply & Lay") {
            $('#ul-suplay').empty();
            $('#ul-suplay').append('<fieldset data-role="controlgroup"> \

http://jsfiddle.net/m7hg2p94/4/

azim hamdan
  • 113
  • 10
3

attr accepts two strings.

The correct way is:

jQuery("#radio_1").attr('checked', 'true');
keroles Monsef
  • 679
  • 7
  • 15
3
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');
dominicbri7
  • 2,479
  • 4
  • 23
  • 33
3

I used jquery-1.11.3.js

Basic Enable & disable

Tips 1: (Radio button type common Disable & Enable)

$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true); 

Tips 2: ( ID selector Using prop() or attr())

$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);

jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);

Tips 3: ( Class selector Using prop() or arrt())

$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);

jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);

OTHER TIPS

$("#paytmradio").is(":checked")   // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled

$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
 $("input:checked", "#paytmradio").val() // get the checked value

index.html

<div class="col-md-6">      
    <label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
    <div id="paymenttype" class="form-group" style="padding-top: inherit;">
        <label class="radio-inline" class="form-control"><input  type="radio" id="paytmradio"  class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
        <label class="radio-inline" class="form-control"><input  type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
    </div>
</div>
venkatskpi
  • 800
  • 6
  • 8
2

try this

 $("input:checked", "#radioButton").val()

if checked returns True if not checked returns False

jQuery v1.10.1
The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
pst
  • 56
  • 4
2

Some times above solutions do not work, then you can try below:

jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));

Another way you can try is:

jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    [Uniform](http://uniformjs.com/) is a jQuery plugin that makes forms prettier, but it does that by adding extra elements. Whenever I update the checked value, the extra element state is not updated, leading to an invisible input that is not checked, but with a visible background element that looks checked. `jQuery.uniform.update()` is the solution! – Denilson Sá Maia Sep 19 '14 at 23:42
1

Try This:

$(document).ready(function(){
  $("#Id").prop("checked", true).checkboxradio('refresh');
});
Sameeraa4ever
  • 568
  • 7
  • 20
  • This won't work without including the file for the `checkboxradio` plugin, which is pointless when you can just use jQuery's built in functions to accomplish this (see accepted answer). – Nathan Jan 02 '15 at 06:48
1

In case you don't want to include a big library like jQuery for something this simple, here's an alternative solution using built-in DOM methods:

// Check checkbox by id:
document.querySelector('#radio_1').checked = true;

// Check checkbox by value:
document.querySelector('#type > [value="1"]').checked = true;

// If this is the only input with a value of 1 on the page, you can leave out the #type >
document.querySelector('[value="1"]').checked = true;
<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-4

Shortest

radio_1.checked

checkBtn.onclick = e=> {
  console.log( radio_1.checked );
}
Select first radio and click button
<!-- Question html -->
<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

<!-- Test html -->
<button id="checkBtn">Check</button>

jsfiddle snippet here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345