无法验证javascript中的复选框

时间:2017-10-12 13:48:52

标签: javascript html

我是JavaScript新手。我需要验证复选框表单。我可以验证单个复选框,但无法验证多个复选框值。

function validate(form) {
  if (form.answer.checked == false) {
    alert('select anwser!'); //able to validate
    return false;
  }

  if (form.answers.checked == false) {
    alert('You must choose any anwsers!'); //unable to validate
    return false;
  }
}
<form id="surveyform" action="#" onsubmit="return validate(this)">
  <input type="checkbox" name="answer" value="answer1" />answer
  <br><br>
  <input type="checkbox" name="answers[]" value="answer1" />answer1
  <input type="checkbox" name="answers[]" value="answer2" />answer2
  <input type="checkbox" name="answers[]" value="answer3" />answer3
  <input type="checkbox" name="answers[]" value="answer4" />answer4
  <br><br>
  <input type="submit">
</form>

2 个答案:

答案 0 :(得分:2)

对于多个复选框,您需要执行以下代码段。

&#13;
&#13;
function validate(form) {
	if(form.answer.checked == false){
		alert ('select anwser!');
		return false;
	}

	var checkans = false;
	ans = form.elements['answers[]'];
	for (var i = 0; i < ans.length; i += 1) {
		if (ans[i].checked) {
			checkans = true;
		}
	}
	if (!checkans) {
		alert ('You must choose any anwsers!');
		return false;
	}
}
&#13;
<form id="surveyform" action="#" onsubmit="return validate(this)">
	<input type="checkbox" name="answer"  value="answer1"  />answer
	<br><br>
    <input type="checkbox" name="answers[]"  value="answer1"  />answer1
	<input type="checkbox" name="answers[]"  value="answer2"  />answer2
	<input type="checkbox"  name="answers[]"  value="answer3"  />answer3
	<input type="checkbox"  name="answers[]"  value="answer4" />answer4
	<br><br>
	<input type="submit">
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试循环遍历answers数组并在每个复选框中检查true,因为您可以使用forEach循环遍历它们。