3

I have a strange behaviour in IE browser.

I have simple form:

<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>

and in 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;
  }
});

Let's assume that I filled all fields correctly.

In Chrome & Firefox, when I press on submit button then works fine, just once time.

In IE (all versions) I have to press two times on the submit form to execute/sumbit the form.

Why ?

I tried also to put after IsValidUrl condition:

$(this).submit();

But no success.

4

1 回答 1

0

You have two options here. On both you need to stop the submit event and validate the form.

  • One is to go through all the fields in the form, add the class error to the invalid ones (if there's any), set the variable result and return (or submit if everything is alright).

  • The other is to stop the test at the first invalid field found, not using the variable result, and return (or submit if everything is alright).

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();
    });
});
于 2013-07-25T08:10:21.703 回答