简体   繁体   中英

validation of multiple checkboxes

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

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

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

jsFiddle .

PHP (example server side code)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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