Stop All Form Submit In My Page
My need is to interrupt all form submit of my webpage and need to add a extra input field to it. I need to do it with js/Jquery. I can do this for single form (using name/ID). But
Solution 1:
In my case all forms are submitted using javascript submit() method
In that case, you can wrap that method. Which is important, because when you call the DOM's HTMLFormElement#submit
method, submit
event handlers are not triggered. (If you use jQuery's submit
method instead, it does trigger handlers before submitting the form.)
Here's how you wrap that 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've tagged your question jquery
, with jQuery:
$("form").each(function() {
var form = this;
var realSubmit = form.submit;
form.submit = function() {
// Do your stuff
// ...
// Submit the form
realSubmit.call(form);
};
});
You'll need to check that your target browsers allow it. Modern ones do.
Here's 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's submit">
<input id="sendjQuery" type="button" value="Send with jQuery's 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>
Solution 2:
You select and find the form in your page using $('form') selector.
it returns all the forms inside your page.
then bind the submit event.
var ajaxFormSubmit = function(){
//write what you need to do
return false;
};
$('form').submit(ajaxFormSubmit);
Post a Comment for "Stop All Form Submit In My Page"