如何检查循环中的所有内容是否为真?

时间:2012-08-30 02:54:22

标签: javascript jquery

我有一个简单的多重问题表单,每个问题有4个答案,用户必须为每个问题选择1个答案。

到目前为止,我可以查看未回答的问题并显示错误消息。

但是现在如果所有问题都得到了解答,我需要表单转到结果页面(我假设window.location?)

如何检查所有问题是否已得到解答?

$('.submit-button').click(function(event){
    $('.validate-message').hide();

    for (var i=1;i<6;i++) {
        var input = $("input[name=q"+i+"]");
        var inputChecked = $("input[name=q"+i+"]:checked");

        if (!inputChecked.val()) { //if an answer is not selected for a question
            $(input).parents('fieldset').append('<div class="validate-message" style="color:red;">Please choose an answer!</div>');

        } else { // if an answer is selected for a question
        }
    }       
    return false;          
});

2 个答案:

答案 0 :(得分:1)

只需使用布尔变量:

$('.submit-button').click(function(event){
    var noErrors = true;  // default to no errors

    $('.validate-message').hide();

    for (var i=1;i<6;i++) {
        var input = $("input[name=q"+i+"]");
        var inputChecked = $("input[name=q"+i+"]:checked");

        if (!inputChecked.val()) { //if an answer is not selected for a question
            noErrors = false;  // an error was found, set noErrors to false
            $(input).parents('fieldset').append('<div class="validate-message" style="color:red;">Please choose an answer!</div>');

        } else { // if an answer is selected for a question
        }
    }       

    if(noErrors) // do stuff

    return false;          
});

答案 1 :(得分:0)

出于兴趣,这是一个简单的JavaScript解决方案。

假设HTML类似于以下内容:

<form id="f0" onsubmit="return validateForm(this);">
  <div>
    <p>Question 1.<br>
      A<input type="radio" value="A" name="q1"><br>
      B<input type="radio" value="B" name="q1"><br>
      C<input type="radio" value="C" name="q1"><br>
      D<input type="radio" value="D" name="q1"><br>
    </p>
    <p>Question 2.<br>
      A<input type="radio" value="A" name="q2"><br>
      B<input type="radio" value="B" name="q2"><br>
      C<input type="radio" value="C" name="q2"><br>
      D<input type="radio" value="D" name="q2"><br>
    </p>
    <input type="reset"  value="Clear answers">
    <input type="submit" value="Submit answers">
  </div>
</form>

验证每个问题已被回答的功能是:

function validateForm(form) {

  var control, controls = form.elements;
  var visited = {};
  var name, radios;

  for (var i=0, iLen=controls.length; i<iLen; i++) {
    control = controls[i];
    name = control.name;

    if (control.type == 'radio' && name && !visited.hasOwnProperty(name)) {
      visited[name] = false;
      radios = form[name];

      for (j=0, jLen=radios.length; j<jLen; j++) {
        visited[name] = visited[name] || radios[j].checked;
      }

      if (!visited[name]) {
        // Question hasn't been answered, cancel submit and do whatever
        alert('There are unanswered questions for ' + name);
        return false;
      }
    }
    // Validation for other controls
    // ...
  }
}