Stop sending any form on my page

I need to interrupt the transfer of all forms of my web page and add an additional input field to it. I need to do this using js / jquery.

I can do this for one form (using name / id). But I need to do this for all 100 forms presented on my site. (In my case, all forms are submitted using the submit() method of the submit ()] form element.)

Can I do this? How to override the actual form.submit() method?

0
source share
2 answers

In my case, all forms are submitted using the javascript submit () method

In this case, you can wrap this method. This is important because when you call the DOM method HTMLFormElement#submit , submit event handlers are not . (If you use the jQuery submit method instead, it starts the handlers before submitting the form.)

Here's how you wrap this function without using any libraries:

 Array.prototype.forEach.call(document.querySelectorAll("form"), function(form) { var realSubmit = form.submit; form.submit = function() { // Do your stuff // ... // Submit the form realSubmit.call(form); }; }); 

... or as you noted your jquery question using jQuery:

 $("form").each(function() { var form = this; var realSubmit = form.submit; form.submit = function() { // Do your stuff // ... // Submit the form realSubmit.call(form); }; }); 

You need to check if your target browsers are allowed. Modern.

Here is a complete example: Live Copy

 <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <meta charset="utf-8"> <title>Example</title> </head> <body> <p>This page adds the q field to a form it submits to Google</p> <form method="GET" action="http://google.com/search" target="_blank"> <input id="sendDOM" type="button" value="Send with DOM submit"> <input id="sendjQuery" type="button" value="Send with jQuery submit"> </form> <script> $("#sendDOM").click(function() { $("form")[0].submit(); }); $("#sendjQuery").click(function() { $("form").submit(); }); // Wrap submit on the forms $("form").each(function() { var form = this; var realSubmit = form.submit; form.submit = function() { // Do your stuff var el = document.createElement("input"); el.type = "hidden"; el.name = "q"; el.value = "kittens"; form.appendChild(el); // Submit the form realSubmit.call(form); }; }); </script> </body> </html> 
+1
source

You select and find the form on your page using the $ ('form') selector.

it returns all forms inside your page.

then bind the dispatch event.

 var ajaxFormSubmit = function(){ //write what you need to do return false; }; $('form').submit(ajaxFormSubmit); 
0
source

All Articles