Intercept form onSubmit - javascript

Is there any way we can intercept the html form's onsubmit event?
In my web application, there are several screens containing forms etc. The issue we are facing is when the user presses any button multiple times, the server gets overloaded with same requests.
Some of the forms have event handlers already attached to them(like onSubmit, button.onClick etc).
One way can be to "inject" my button disable code by going through all the screens.
But what I am looking for is a generic solution which can be applied to all the screens by just including the script where the function is written.
I know I can setup callback using jQuery (capturing onSubmit for form), but in the issue in this case is if any screen has a onSubmit registered already, it may not get called.
Any help in this regard appreciated!

I think this piece of code is a good place to start. It should be placed in separate file and included where you want to use it (if you appear to have global list of scripts - its a good place for it)
var suppressed_items = [];
function allowOnlyOne(item,e){
if (jQuery.inArray(item, suppressed_items)==-1){
//hi little item, I haven't saw you before, please go on... but I remember you
suppressed_items.push(item);
return true;
}
else{
//Hey, you have been submitted already, stay where you are!
return false; //or e.preventDefault(), it's a matter of faith :)
}
}
jQuery(document).ready(function(){
//don't worry, it won't replace your `ready` handlers, but just append new handler
jQuery("from").submit(function(e){
return allowOnlyOne(jQuery(this),e);
});
});
You can use the allowOnlyOne function with any item you wish. So, for example to allow single click on all hyperlinks, inside that ready handler add:
jQuery("a").click(e){
return allowOnlyOne(jQuery(this),e);
}
I hope you get the basic idea: catch the event, get the ID of the element that trigger it, fed it to AllowOnlyOne along with event.
Of course you can wrap it all around into self-executing closure to achieve incapsulation and so on...

If you already have jQuery I suggest you use it... All you need to do is make sure is that your form's onsubmit do not have a "return false" or else it can block jQuery's on submit.
Here's what you need to do:
Remove any return false from your form's onsubmit (if any). Don't worry we'll take care of this later in jQuery.
Add a class to your forms... something like "disableOnSubmit". Example:
<form action="something" onsubmit="yourExistingCode" class="disableOnClick">
</form>
OR
<form action="something" onsubmit="yourExistingCode" class="someOtherClass disableOnClick">
</form>
Implement a code similar to:
<script type="text/javascript">
$(document).ready(function(){
$('form.disableOnClick').submit(function(e){
// preventDefault() does the same as "return false;". It
// will not submit the form. If you're not using return false
// and want the form to be submitted remove the line below
e.preventDefault();
// Now diable any submit button
$('input[type=submit], button[type=submit]').attr('disabled, 'disabled');
});
});
</script>

Related

Search form isn't passing through the first time?

Hi Guys!
The problem is that I have a form which searches etc. The thing that go's wrong is that the first time you use the form nothing happens and it go's to domain/?. I have no idea what the problem is. I've tried a lot of things but nothing seems to be doing the trick. Thanks!
It seems like it doesn't prevent the default action on the first run because I've tried and a console.log inside this function won't run.
$(function () {
$('#search-bar').on('submit', function (e) {
var y = $('#search').val().toLowerCase();
if (y === 'location') {
geoSearch();
} else {
qCall(y);
}
x.val('');
e.preventDefault;
});
});
The forms HTML has not action or method
You probably cut down the form submit with e.preventDefault. According to W3C definition, the preventDefault javascript function do the following :
Definition and Usage The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL
So removing e.preventDefault(); from your code should do the trick.
And by the way, you forgot the double '()' behind the function name. I'm pretty sure you made the mistake only on the code posted, but worth the warning, we never know.

How to handle Ajax-generated form in Javascript?

So I use this Javascript to handle forms:
$(':submit:not(.form-default-submit)').click(function(event) {
//Disable normal form submission, handle using ajax
});
It works correctly in most cases. So any submit element with the class form-default-submit is ignored, and all others are handled in this Javascript.
But I've just noticed that this doesn't work for Ajax-generated content. Which I'm guessing is because this code is run on page load, before the Ajax content is loaded.
I see people using:
$(document).on("click", selector, function(e){
As a fix for this. But in my case, I don't just apply it to the element directly. I have that condition to allow exceptions for elements with the class form-default-submit.
Is the only way to do this with the new Ajax-supported method to have an if statement within the function checking if the element has a particular class? Or can I do this within the selector itself? This is a bit above my current ability, so thanks for any help!
Try this:
$(document).on( "click",":submit:not(.form-default-submit)", function(e){
You can bind the submit event directly to the form and return false. This will also catch a form sent by using the enter key.
$("#form").on("submit", function(event){
// Send form data by AJAX
$.post(...);
// Prevent form to be sent the regular way
return false;
});

Disabling default alert that normally appears on submit

I am trying to disable the default confirm box that fires onSubmit. I have been trying for a while now with no success. This is what I tried...
My Markup
<form method="post" action="special.php" id="myForm" onsubmit="return confirm('Are you sure you ready to submit this order?\n\n')">
//input fields
</form>
My JavaScript
$('.excelDL').click(function(){
$('#myForm').trigger('submit', function(e){
window.alert = function() {}; //overwrite default alert
$.post('mail.php', $(this).serialize(), function (data) {})
e.preventDefault();
});
});
The confirm box appears because of the onsubmit="return confirm(...)" attribute on your <form>. If you remove that, the confirm dialog will not appear when you submit the form via JQuery.
If you need this confirmation to appear except when submit the form using your $('#myForm').trigger(...) code, then remove your window.alert = function() {}; line and add the line $('#myForm').submit(function(){ return true; }); before you call .trigger(). This will remove the onsubmit handler for the form before submitting it.
It's generally a bad idea to try to override the built in methods (like confirm()) it's a much better idea to just not call them.
To begin with you're not firing an alert, you're firing a confirm. so change
window.alert = function() {};
to
window.confirm = function() {};
then move it outside the submit function so that it overwrites the native function before the submit happens.
The jQuery docs don't mention that you can pass a function to .trigger as second parameter and I don't believe it actually works.
If you just want to make the Ajax request without triggering .submit, you can make the call directly
$.post('mail.php', $('#myForm').serialize(), function (data) {});
or trigger only event handlers bound with jQuery using .triggerHandler. In both cases a native submit event won't generated and event handlers bound with other ways won't be triggered.
As others said, binding all event handlers with jQuery instead of using inline event handlers would improve the code as well.
just take this out
onsubmit="return confirm('Are you sure you ready to submit this order?\n\n')"
then you can manually decide when to use the alert in this function
$('#myForm').trigger('submit', function(e){
// cal the confirm here , or write your own pop up script that looks the way you want.
});

Capturing jQuery form submit event

I don't know what is wrong with that, because I was following at every step the tutorial from jquery.com regarding the form submit event.
My Javascript:
[Ofc. latest jQuery library is included].
<script type="text/javascript">
$("form#addFav").submit(function(event) { event.preventDefault(); alert("hello"); });
</script>
Have also tried with the $(document).ready() event:
$(document).ready(function(){
$("form#addFav").submit(function(event) { event.preventDefault(); alert("hello"); });
});
Here is my HTML form code:
<form action="" id="addFav">
<input type="text" name="name" class="thin-d"/>
<input type="submit" value="Send"/>
</form>
So, regarding the above Javascript code, it is supposed to work (I mean it should prevent default action [submitting form] and send the alert then), but it all doesn't work - have tried with thousands of combinations, but I fail'd. So I'm waiting for your solutions. I'd appreciate every one.
You probably have some syntax error or somthing like that somewhere else, because what you have just works.
Are you sure there aren't any JS errors?
P.S. I would alwyas go for the latter code to ensure that the elements are in the DOM before trying to attach events.
For anyone else who has the same problem, and still struggling to solve this issue, try to see if you have illegally reused the id, and try changing the form id to something unique.
I had accidentally given the id to two different DOM elements and the event was being bound to the first element with the respective id and my form was the second one so it was never captured. This had me pulling my hairs for quiet a long.
I just recently ran into the same issue. Jquery on submit would not work on the form, however just changing it to click event worked fine. Still at a loss why .on(submit) or .submit() events will not recognize the form.
$("form#addFav").click(function (event) {
event.preventDefault(); alert("hello");
$(this).submit();
});
this question is old but.. you might have had another submit events firing before yours fired. If these other events contained "return false;" statement then the event execution got interrupted and your code never fired. To put your code BEFORE these events you might use ONSUBMIT form attribute where you can put code that will fire before or at the same time as other events.

Disable action in form when using AJAX commands?

When one uses AJAX commands with Jquery, is it necessary to disable form action parameter in the HTML? The load URL and the action point to the same place, so is it necessary to have the action parameter?
You should use the event object's preventDefault() method, which will disable any default behavior associated with the element type. This is very important for links and form submit buttons.
For example:
<!-- you have this link -->
<a id="clickme" href="test.html">Click me</a>
You can disable the loading of test.html by using preventDefault()
$('#clickme').click(function(event) {
event.preventDefault();
// ...
});
You can also return false in your click function for the same effect.
In this case I think is useful only for clarity of code. When you put your code to make the AJAX call you can get the url from the form's action but that depends on you.
Try to be clear and consistent it's my advice.
If you are submitting the form via Ajax, then you just need to make sure there is not a way for the form to be submitted traditionally. You can either remove the form tags themselves, remove the actions, or remove any submit buttons. You can also capture the submit event of the form and just return false to prevent the form from doing a postback submit.

Categories