我必须使用jquery框架在IE中按下两次提交按钮才能提交表单

I have to press submit button twice in IE using jquery framework to submit form

本文关键字:提交 两次 按钮 表单 jquery 框架 IE      更新时间:2023-09-26

我在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&火狐浏览器,当我按下提交按钮,然后工作正常,只有一次。

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

为什么?

我也试着把IsValidUrl条件后:

$(this).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();
    });
});