我在IE浏览器中有一个奇怪的行为。

我有一个简单的表格:

<form name="test" id="test" action="some_url_here" method="post">
  <input type="text" name="url" id="url" class="required" />
  <input type="text" name="page" id="page" class="required" />
  ...
  <input type="submit" name="submit" value="Submit" />
</form>

在JS中:
var result = true;

$("#test").on("submit", function(){
   $(".required").removeClass("error");
   $.each($("input.required"), function(k, v) {
      if($(this).val() === '') {
         $(this).addClass("error");
         result = false;
         return false;
      }
   });

  if(result) {
    if(!IsValidUrl($("input[name='url']").val()){
       $("input[name='url']").addClass("error");
       return false;
    }
  } else {
    return false;
  }
});

假设我正确填写了所有字段。

在Chrome和Firefox中,当我按“提交”按钮时,则只能运行一次。

在IE(所有版本)中,我必须在提交表单上按两次以执行/汇总表单。

为什么呢

我还尝试过IsValidUrl条件:
$(this).submit();

但是没有成功。

最佳答案

您在这里有两个选择。两者都需要停止Submit事件并验证表单。

  • 一种方法是遍历表单中的所有字段,将类错误添加到无效的字段中(如果有的话),设置变量结果并返回(或在一切正常的情况下提交)。
  • 另一种方法是在找到的第一个无效字段处停止测试,而不使用变量结果,然后返回(或在一切正常的情况下提交)。

  • JS
    $(function () {
        $("#test").on("submit", function (e) {
            // Stop the submit, because you need to validate the form before proceeding.
            e.preventDefault();
    
            // Check the comments below to decide for the use of the variable.
            var result = true;
    
            $(".required").removeClass("error");
            $.each($("input.required"), function (k, v) {
                // Test for empty fields or, if it's the URL, check whether is valid.
                if ($(this).val() === "" || ($(this).attr("name") == "url" && !IsValidUrl($(this).val())) {
                    // Add class error to the invalid fields.
                    $(this).addClass("error");
    
                    // At this point, you could just return false stopping the loop,
                    // or keep going to make sure all the invalid fields will get the
                    // class error. In this case, you can still use the variable result.
                    result = false;
    
                    // Keep going, so, no return.
                    // return false;
                }
            });
    
            // If you decided to carry on through all the fields, and don't return
            // false at the first error, test for the result value.
            // As this is the case...
            if (!result) return false;
            else $(this).submit();
    
            // If you didn't return previously...
            // $(this).submit();
        });
    });
    

    07-26 07:59
    查看更多