检查是否选中任何单选框或复选框

Check if any radio or checkbox is selected

本文关键字:复选框 是否 检查 任何单      更新时间:2023-09-26

如何使用jQuery来确定是否选中复选框或单选按钮?

这是我的HTML:

<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
<span id="check1">check</span>
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>
<span id="check2">check</span>

以下是一些伪JavaScript:

$("#check1").click(function(){
    if(any radio is selected){
       alert("Please select one radio");
    }
})
$("#check2").click(function(){
    if(any checkbox is selected){
       alert("Please select minimum one checkbox");
    }
})

这在jQuery中是可能的?

jsfiddle上的实时示例:http://jsfiddle.net/BghzK/谢谢你的帮助!

您可以在选择器表达式中使用:checked伪选择器。将其与.length结合起来查看返回了多少。在这种情况下,我们获取所有选定的单选按钮,并查看长度是否为零,表示没有选定任何单选按钮。

http://jsfiddle.net/mrtsherman/BghzK/2/

$("#check1").click(function(){
    if($('input[type=radio]:checked').length == 0){
       alert("Please select one radio");
    }
})
$("#check2").click(function(){
    if($('input[type=checkbox]:checked').length == 0){
       alert("Please select minimum one checkbox");
    }
})
​
if( !$(':radio:checked').length){
    alert('Please select one radio');
}

您需要在选择器中使用is(":checked")。下面的示例代码:

 $(function() {
           $("#check1").click(function(){
                if(!($("input[name='sex']").is(":checked"))){
                   alert("Please select one radio");
                }
             })
        $("#check2").click(function(){
             if(!($("input[name='vehicle']").is(":checked"))){
               alert("Please select minimum one checkbox");
            }
        })
        });

使用jquery Validation插件会自动完成。对于单选按钮,您只需要将元素required制成.

var rdo = $('input[name="group"]:checked');
var boxes = $('input[type="checkbox"]:checked');
if(rdo.length == 0) 
    alert("Please select one radio");
if(boxes.length == 0)
    alert("Please select minimum one checkbox");

您可以通过这种方式尝试这个简单的

   var chkvalue =   $('input[name="sex"]:checked').val();
    if(chkvalue =="")
    {
     alert("Please checked the radio button");
     return;
    }