Problem
I’m using jQuery to check a radio button. My code is as follows:
<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 any other suggestions? What am I overlooking?
Asked by Alexis
Solution #1
Use the following syntax for jQuery versions equal to or greater than (>=) 1.6:
$("#radio_1").prop("checked", true);
Use: for versions earlier to () 1.6.
$("#radio_1").attr('checked', 'checked');
After that, you might wish to execute click() or change() on the radio button. More information can be found in the comments.
Answered by Mike Thomsen
Solution #2
Try this.
In this case, I’m using its input name and value to target it.
$("input[name=background][value='some value']").prop("checked",true);
It’s also worth noting that apostrophes will operate in the situation of multi-word value.
Answered by Vladimir Djuricic
Solution #3
Prop() is a new function added in jQuery 1.6 that serves the same purpose.
$("#radio_1").prop("checked", true);
Answered by Umesh Patil
Solution #4
Option that is short and easy to read:
$("#radio_1").is(":checked")
You can use it in a “if” statement because it returns true or false.
Answered by Petr Lazarev
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');
Answered by Lakshmana Kumar
Post is based on https://stackoverflow.com/questions/5665915/how-to-check-a-radio-button-with-jquery