簡體   English   中英

我必須在IE中使用jquery框架兩次按提交按鈕提交表單

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

我在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條件之后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();
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM