Javascript 如何检查单选按钮是否使用 JQuery 检查?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8725172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check radio button is checked using JQuery?
提问by Bader
I have two radio buttons in one group, I want to check the radio button is checked or not using JQuery, How ?
我在一组中有两个单选按钮,我想使用 JQuery 检查单选按钮是否被选中,如何?
回答by nnnnnn
Given a group of radio buttons:
给定一组单选按钮:
<input type="radio" id="radio1" name="radioGroup" value="1">
<input type="radio" id="radio2" name="radioGroup" value="2">
You can test whether a specific one is checked using jQuery as follows:
您可以使用 jQuery 测试是否检查了特定的,如下所示:
if ($("#radio1").prop("checked")) {
// do something
}
// OR
if ($("#radio1").is(":checked")) {
// do something
}
// OR if you don't have ids set you can go by group name and value
// (basically you need a selector that lets you specify the particular input)
if ($("input[name='radioGroup'][value='1']").prop("checked"))
You can get the value of the currently checked one in the group as follows:
您可以通过以下方式获取当前选中的组中的值:
$("input[name='radioGroup']:checked").val()
回答by Sudhir Bastakoti
//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});
回答by Lead Developer
This is best practice
这是最佳做法
$("input[name='radioGroup']:checked").val()
回答by Sadee
jQuery 3.3.1
jQuery 3.3.1
if (typeof $("input[name='yourRadioName']:checked").val() === "undefined") {
alert('is not selected');
}else{
alert('is selected');
}
回答by Yasin Patel
Try this:
尝试这个:
var count =0;
$('input[name="radioGroup"]').each(function(){
if (this.checked)
{
count++;
}
});
If any of radio button checked than you will get 1
如果选中任何单选按钮,您将获得 1
回答by Antony
Taking some answers one step further - if you do the following you can check if any element within the radio group has been checked:
更进一步地回答一些问题 - 如果您执行以下操作,您可以检查无线电组中的任何元素是否已被检查:
if ($('input[name="yourRadioNames"]:checked').val()){
(checked) or if (!$('input[name="yourRadioNames"]:checked').val()){
(not checked)
if ($('input[name="yourRadioNames"]:checked').val()){
(选中)或if (!$('input[name="yourRadioNames"]:checked').val()){
(未选中)
回答by reshma
Radio buttons are,
单选按钮是,
<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">
to check on click,
检查点击,
$('.radioButtons').click(function(){
if($("#radio_1")[0].checked){
//logic here
}
});
回答by radu florescu
Check this one out, too:
也看看这个:
$(document).ready(function() {
if($("input:radio[name='yourRadioGroupName'][value='yourvalue']").is(":checked")) {
//its checked
}
});