MayTheSchwartzBeWithYou
MayTheSchwartzBeWithYou

Reputation: 1177

jQuery form submitting script does not work

I try to prevent a form submitting, with the following script, but it always does. I have even tried preventDefault() on document load, but it does not work.

$("form").submit(function() {
      if ($("input").eq(3).val() == $("input").eq(4).val()) {
            $("span").text("Validated...").show();
        return true;
      }

      $("span").text("Passwords do not match!").show().fadeOut(1000);
      return false;
});

Upvotes: 0

Views: 200

Answers (3)

MayTheSchwartzBeWithYou
MayTheSchwartzBeWithYou

Reputation: 1177

In order for this to close I think I have found something, but it's absurd at best. My functions work when they are in a $(document).ready. Why? I would be glad to listen to your advice.

$(document).ready(function(){

$("form").submit(function() {
      if ($("input").eq(3).val() == $("input").eq(4).val()) {
            $("span").text("Validated...").show();
        return true;
      }

      $("span").text("Passwords do not match!").show().fadeOut(1000);
      return false;
});

 });

Upvotes: 0

Phil
Phil

Reputation: 11175

My suggestion, or the way I normally go about this is like this:

$("form").submit(function(e) {
    e.preventDefault(); // form never fires unless I want it to

    if( condition == true ) {
        $(this).submit();
    } else {
        //Don't submit
    }
}

Here is a great explanation of why preventDefault() > return false

Upvotes: 0

Shmiddty
Shmiddty

Reputation: 13967

$("form").submit(function(e) {
      if ($("input").eq(3).val() == $("input").eq(4).val()) {
            $("span").text("Validated...").show();
      }
      else{
        $("span").text("Passwords do not match!").show().fadeOut(1000);
        e.preventDefault();
      }
});

You need to use preventDefault() to cancel the action. Note the parameter e that I added to the anonymous function call.

Upvotes: 1

Related Questions