本文翻译自:How to check a radio button with jQuery?
I try to check a radio button with jQuery. 我尝试用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: 和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? 我错过了什么?
#1楼
参考:https://stackoom.com/question/Nlxj/如何使用jQuery检查单选按钮
#2楼
Short and easy to read option: 简短易读的选项:
$("#radio_1").is(":checked")
It returns true or false, so you can use it in "if" statement. 它返回true或false,因此您可以在“if”语句中使用它。
#3楼
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. 很高兴知道:在多字值的情况下,它也会因为撇号而起作用。
#4楼
Try this. 试试这个。
To check Radio button using Value use this. 要使用Value检查单选按钮,请使用此选项。
$('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. 要使用ID检查单选按钮,请使用此选项。
$('#radio_1').attr('checked','checked');
Or 要么
$('#radio_1').prop('checked','checked');
#5楼
试试这个
var isChecked = $("#radio_1")[0].checked;
#6楼
The $.prop
way is better: $.prop
方式更好:
$(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();
});
});