检查是否选择了任何收音机或复选框
我如何使用jQuery来确定是否选中了复选框或单选按钮?
这是我的HTML:
check check
这是一些伪的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
pseudoselector。 将此与.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; }