2021-03-12

jQuery如何判断复选框至少选择一个?

我们经常会遇到多选框至少需要选择一项的需求,这个需要js去进行验证,以下是jQuery的判断方法:


HTML代码:

 

<h2>请选择您的爱好:</h2><form action="" method="post" id="form"><label><input type="checkbox" name="hobby" value="上班" />上班</label><label><input type="checkbox" name="hobby" value="运动" />运动</label><label><input type="checkbox" name="hobby" value="看书" />看书</label><label><input type="checkbox" name="hobby" value="上网" />上网</label><label><input type="checkbox" name="hobby" value="网购" />网购</label><label><input type="checkbox" name="hobby" value="其他" />其他</label><button type="reset">重 置</button><button type="button" onclick="Submit()">提 交</button></form>

 

  

 

jQuery写法:

 

function Submit() {var checkOne = false; //判断是否被选择条件var chboxVal = []; //存入被选中项的值var checkBox = $('input[name = hobby]'); //获得得到所的复选框for (var i = 0; i < checkBox.length; i++) {//如果有1个被选中时(jquery1.6以上还可以用if(checkBox[i].prop('checked')) 去判断checkbox是否被选中)if (checkBox[i].checked) {checkOne = true;chboxVal.push(checkBox[i].value)//将被选择的值追加到};};if (checkOne) {alert("您选择爱好对应的value是:" + chboxVal);} else {alert("对不起:至少要选择一项爱好哦!");};};

  文章出处  (我爱捣鼓)









原文转载:http://www.shaoqun.com/a/621657.html

跨境电商:https://www.ikjzd.com/

bap:https://www.ikjzd.com/w/1492

rfq:https://www.ikjzd.com/w/251


我们经常会遇到多选框至少需要选择一项的需求,这个需要js去进行验证,以下是jQuery的判断方法:HTML代码:<h2>请选择您的爱好:</h2><formaction=""method="post"id="form"><label><inputtype="checkbox&
蜜芽宝贝官网:https://www.ikjzd.com/w/1320
史泰博办公用品:https://www.ikjzd.com/w/2112
outfit:https://www.ikjzd.com/w/938
Sumall:https://www.ikjzd.com/w/392
口述:同居3年 我被折磨得身心俱疲(2/2):http://lady.shaoqun.com/m/a/82791.html
口述:和不喜欢的女人第一次约会谁买单?(2/2):http://lady.shaoqun.com/m/a/110025.html

No comments:

Post a Comment