开发者

validation of multiple checkboxes

开发者 https://www.devze.com 2023-02-16 10:31 出处:网络
I have a form in which i have many questions whose answers are given through checkbo开发者_如何学JAVAxes, now i have to validate that in all the questions containing answers in checkboxes one have to

I have a form in which i have many questions whose answers are given through checkbo开发者_如何学JAVAxes, now i have to validate that in all the questions containing answers in checkboxes one have to check at least one checkbox ohterwise an alert message appears and i want to do it with a single function and also want to know that how do i call the function in my html part.so send ur answers.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消