Advertisement
Advertisement


How to check a radio button with jQuery?


Question

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?

2020/06/25
1
900
6/25/2020 3:01:50 PM

Accepted Answer

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.

2017/12/03
1482
12/3/2017 4:44:42 AM

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.

2015/02/19

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

$("#radio_1").prop("checked", true); 
2012/01/03

Short and easy to read option:

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

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

2013/04/22

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');
2013/06/21

Try This:

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

http://jsfiddle.net/nwo706xw/

2015/01/15

Source: https://stackoverflow.com/questions/5665915
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]