tudouguaishou

我们经常会遇到多选框至少需要选择一项的需求,这个需要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.woaidaogu.com   (我爱捣鼓

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2021-12-09
  • 2021-07-12
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-14
  • 2021-08-05
  • 2021-12-09
  • 2021-12-09
相关资源
相似解决方案