检查是否选择了任何收音机或复选框

检查是否选择了任何收音机或复选框

本文介绍了检查是否选择了任何收音机或复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的HTML:


$

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

 < form> 
< input type =radioname =sexvalue =male/>男性< br />
< input type =radioname =sexvalue =female/>女
< / form>

< span id =check1>检查< / span>

< form>
< input type =checkboxname =vehiclevalue =Bike/>我有一辆自行车< br />
< input type =checkboxname =vehiclevalue =Car/>我有一辆车
< / form>

< span id =check2>检查< / span>

以下是一些psuedo JavaScript:

<$ p点击(功能(){
如果(任何收音机被选中){
alert(请选择一个收音机); $($#$)点击(功能(){
if(任何复选框被选中){
alert(b
$ b $)

$(#check2 请选择至少一个复选框);
}
})

它是可能的jQuery?



在jsfiddle上的实例:
感谢您的帮助!

解决方案

您可以利用:在选择器表达式中检查伪选择器。将此与 .length 结合以查看已返回的数量。在这种情况下,我们得到所有选定的单选按钮,看看长度是否为零,表示没有被选中。



点击(函数(){
if($('input [type = radio]:checked')。length == 0){
alert(请选择一个电台);
}
})

$(#check2)。click(function(){
if($ ('input [type = checkbox]:checked')。length == 0){
alert(请选择最少一个复选框);
}
})



How would I use jQuery to determine if a checkbox or radio button is checked or not?

Here is my 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>

Here is some psuedo 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");
    }
})

It is possible in jQuery?

Live example on jsfiddle: http://jsfiddle.net/BghzK/Thanks for help!

解决方案

You can make use of the :checked pseudoselector in your selector expression. Combine this with .length to see how many have been returned. In this case we get all selected radio buttons and see if length is zero, indicating that none have been selected.

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");
    }
})

​

这篇关于检查是否选择了任何收音机或复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:15