How to check a radio button with jQuery?

How to check a radio button with jQuery?

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



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?

Solutions/Answers:

Solution 1:

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.

Solution 2:

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.

Solution 3:

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

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

Solution 4:

Short and easy to read option:

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

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

Solution 5:

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

Solution 6:

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