user1460153
user1460153

Reputation:

setTimeout in form.submit() method does not work

I am trying setTimeout() function in form submit. However before executing the function the form gets submitted and anything inside the timeout function is not getting executed. Below is the code snippet.

$(window).load(function () {
     $("#myform").submit(function() {
          setTimeout(function(){
               alert("me after 1000 mili seconds");
               return false;              
          }, 1000);

    });
};

Kindly help me on how to resolve this issue...

Upvotes: 2

Views: 21031

Answers (4)

George Mickleburgh
George Mickleburgh

Reputation: 1217

If you want to disable the submit action on the form, you could try:

$(window).load(function () {
     $("#myform").submit(function(e) {
          e.preventDefault();
          setTimeout(function(){
          alert("me after 1000 mili seconds");
          return false;

        }, 1000);

    });
});

Upvotes: 1

Devang Rathod
Devang Rathod

Reputation: 6736

First of all you forgotten closing brace ) in last line

$(window).load(function () {
     $("#myform").submit(function(e) {
          e.preventDefault();
          setTimeout(function(){
          alert("me after 1000 mili seconds");
          return false;

        }, 1000);

    });
});
 ^---- here you forgotten to put brace.

Upvotes: 0

karaxuna
karaxuna

Reputation: 26940

$(window).load(function () {
     var submit = false;
     $("#myform").submit(function(e) {
          setTimeout(function(){
              alert("me after 1000 mili seconds");
              submit = true;
              $("#myform").submit(); // if you want            
          }, 1000);
          if(!submit)
              e.preventDefault();
     });
};

Upvotes: 4

BenM
BenM

Reputation: 53198

The form is submitting straight away. You need to delegate the default action. This should work for you:

$(window).load(function () {
     $("#myform").submit(function(e) {
          e.preventDefault();

          setTimeout(function(){
              alert("me after 1000 mili seconds");
          }, 1000);
    });
});

Please see this jsFiddle demo.

Upvotes: 2

Related Questions