简体   繁体   English

验证多个复选框

[英]validation of multiple checkboxes

我有一个表格,其中我有很多问题是通过复选框给出的,现在我必须验证在复选框中包含答案的所有问题中,必须至少选中一个复选框,否则会出现警报消息,我想这样做一个单一的功能,还想知道我该如何在我的html part.so中调用该功能。

HTML 的HTML

<input type="checkbox" name="question[apples]" value="1" id="apples" />
<label for="apples">Do you like apples?</label> 

<input type="checkbox" name="question[shoes]" value="1" id="shoes" />
<label for="shoes">Do you like shoes?</label> 

jQuery jQuery的

if ($('#my-form :checkbox:checked').length == 0) {
    alert("You must answer at least one question');
}

jsFiddle . jsFiddle

PHP (example server side code) PHP(示例服务器端代码)

if (empty($_POST['question'])) {
  // Go back and pick at least one!
}

You can code your answers options in following manner, where in giving same name to the input element to represent a group of answer. 您可以按照以下方式对答案选项进行编码,即在输入元素中使用相同的名称表示一组答案。

<label><input type="checkbox" name="Question1" value="Ans1"/>Answer 1</label>
<label><input type="checkbox" name="Question1" value="Ans2"/>Answer 2</label>
<label><input type="checkbox" name="Question1" value="Ans3"/>Answer 3</label>

<label><input type="checkbox" name="Question2" value="Ans1"/>Answer 1</label>
<label><input type="checkbox" name="Question2" value="Ans2"/>Answer 2</label>
<label><input type="checkbox" name="Question2" value="Ans3"/>Answer 3</label>

Use onSubmit event to call a Javascript for validation and use validateAns (provided below) passing the question name (Question 1 or Question2 from this example) as an argument. 使用onSubmit事件来调用Java脚本进行验证,并使用validateAns(如下提供)将问题名称(此示例中的问题1或Question2)作为参数传递。

function validateAns (questionName) {
  var ansInput = document.getElementsByName(questionName);
  var answered = false;
  for (var i = 0; i < ansInputs.length; i++) {
    if (ansInput[i].checked) {
      answered = true;
      break;
    }
  }
  if (!answered) {
    alert('Answer question ' + questionName);
    return false;
  }
  return true;
}

This should do the trick. 这应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM