为什么即使在满足if条件之后,它还会进入其他部分?

时间:2014-02-28 13:12:19

标签: javascript jquery forms validation checkbox

我遵循表单的HTML代码:

<form name="question_issue_form" id="question_issue_form" action="question_issue.php">
          <table class="trnsction_details" width="100%" cellpadding="5">
            <tbody>    
              <tr>
                <td></td>
                <td>
                  <input type="checkbox" name = "que_issue[]" value = "Question is wrong" id ="chkQueWrong">Question is wrong</input>
                </td>
              </tr>
              <tr>
                <td></td>
                <td><input type="checkbox" name = "que_issue[]" value = "Answers are wrong" id ="chkAnsWrong">Answers are wrong</input></td> 
              </tr>
              <tr>
                <td></td>
                <td><input type="checkbox" name = "que_issue[]" value = "Question direction is incorrect" id ="chkDirIncorrect">Question direction is incorrecct</input></td>                
              </tr>
              <tr>
                <td></td>
                <td><input type="checkbox" name = "que_issue[]" value = "Other" id ="chkOther">Other</input></td>          
              </tr>
              <tr>
                <td></td>
                <td class="set_message" style="display:none;"><textarea name="que_issue_comment" rows="4" cols="25" maxlength="100"></textarea></td>      
              </tr>
              <tr>
                <td></td>
                <td><input type="submit" name="submit" value="Submit" id="report_question_issue"/></td>
              </tr>
            </tbody>
          </table>
        </form>

我想在提交表单之前验证表单,以便从上述所有复选框中选中至少一个复选框,并且当选中值为“Other”的复选框时,文本区域不应为空白。为此,我尝试了以下代码,但即使选择了一个或多个复选框,它也会显示警告。文本区域验证也没有正常工作。在提交表格之前,有谁可以帮我纠正这个验证码?如果抛出一个错误,表单不应该提交。以下是我尝试的jQUery代码。

$(document).ready(function () {
  $('#chkOther').click(function () {
      $('.set_message').toggle(this.checked);
  });

  //This function is use for edit transaction status
  $(document).on('click', '#report_question_issue', function (e) {

      e.preventDefault();

      //$.colorbox.close();

      //for confirmation that status change
      var ans = confirm("Are you sure to report the question issue over?");
      if (!ans) { //alert("Yes its false");
          return false;
      }

      var post_url = $('#post_url').val();

      var checkbox = document.getElementsByName("que_issue[]");

      var checkedAtLeastOne = false;

      $('input[type="checkbox"]').each(function () {
          if ($(this).is(":checked")) { alert("In If");
              //atleast one is checked
              checkedAtLeastOne = true;
          } else { alert("In Else");
              //error
              alert("Check at least one checkbox");
          }

          var other = document.getElementById("chkOther");
          var textfield = document.getElementByName("que_issue_comment");
          if ($(other).is(":checked")) {
              if ($(textfield).val().length == 0) {
                  //error
                  alert("Fill in the textarea");
              }
          }
      });

      $.ajax({
          type: "POST",
          url: post_url,
          data: $('#question_issue_form').serialize(),
          dataType: 'json',
          success: function (data) {
              alert("The values have been inserted");
          }
      });
  });
});

2 个答案:

答案 0 :(得分:2)

if语句多次执行,每个复选框一次。即使已选中其他复选框,您也会看到未选中的每个复选框的警报。你需要彻底改变逻辑;迭代遍历所有查找复选框,并在找到迭代后立即停止迭代。

然后,在检查完所有内容后,确定是否需要显示警报。

答案 1 :(得分:1)

您的if条件正在检查您网页中的每个复选框。这就是为什么它会转向其他部分并警告Check at least one checkbox。为了避免这种情况,请尝试以下代码,

$(document).ready(function() {
    $('#chkOther').click(function() {
        $('.set_message').toggle(this.checked);
    });
    //This function is use for edit transaction status
    $(document).on('click', '#report_question_issue', function(e) {
        var submit = true;
        e.preventDefault();
        //$.colorbox.close();
        //for confirmation that status change
        var ans = confirm("Are you sure to report the question issue over?");
        if (!ans) { //alert("Yes its false");
            submit = false;
        }
        var post_url = $('#post_url').val();
        var checkbox = document.getElementsByName("que_issue[]");
        var checkedAtLeastOne = false;
        $('input[type="checkbox"]').each(function() {
            if ($(this).is(":checked")) {
                checkedAtLeastOne = true;
                return false; //to break from each()
            }
        });
        if (checkedAtLeastOne) {
            //alert("In If");
            var other = $("#chkOther");
            var textfield = $("[name=que_issue_comment]");
            if (other.is(":checked")) {
                if ($.trim($(textfield).val()).length == 0) {
                    //error
                    alert("Fill in the textarea");
                    submit = false;
                }
            }
        }
        else {
            alert("Check at least one checkbox");
            submit = false;
        }
        if (submit) {
            $.ajax({
                type: "POST",
                url: post_url,
                data: $('#question_issue_form').serialize(),
                dataType: 'json',
                success: function(data) {
                    alert("The values have been inserted");
                }
            });
        }
        else {
            alert("Fix the error");
        }
    });
});

Fiddle