简体   繁体   中英

Recursive jQuery submit function doesn't submit the form

I need some code to run right after the submit button has been clicked and before the form has actually been submitted. I've stripped the code and left only the parts needed to show you the problem. What I need the code to do is go inside the submit function, but instead of submitting the form call the function again. The form should submit only in that second iteration. Except it doesn't. The code is fully executed as it should but the form doesn't submit in the end.

I would appreciate it if someone can explain why.

Here's the code (simplr-reg's the form's name):

<script>

var reallySubmit = false;

$(‘#simplr-reg’).submit(function(event)
{    
   if (false == reallySubmit)
   {
      reallySubmit = true;
      $(‘#simplr-reg’).submit(); 
      event.preventDefault();
      return false; 
   }
   else
   {
      return true;
   }
});

</script>
$("#simplr-reg").submit(); 

That says "call the submit method on the jQuery selection". You have a jQuery submit handler bound to the selection. Since you have triggered the event on the jQuery selection, the jQuery handler is also triggered.

If you trigger the event on the native DOM form object ( this within the submit handler), the jQuery handler will not be triggered, so you won't go round in circles. Call the form.submit method:

this.submit();

Change it from a 'submit' event to a 'click' event and attach it to the button itself rather than the form?

ETA: be sure to 'return false' on your non-submit case.

$("#simplr-reg-submit").click(function()
{    
      alert("1st iteration");
      $("#simplr-reg").submit();
       return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM