html form button to stop multiple submissions - javascript

I have this form that submits to work.php.
What I want to do is disable the submit button when the form is submitted, then re-enable it after 5 seconds or so, so I don't get multiple posts.
How can I do this?
Also, if I press the enter key in one of the text boxes while the submit button is not clickable then it will redirect me to work.php which don't want to happen.
<form method="post" action="work.php">
<strong>Message:</strong>
<input type="text" id="message" name="message" class="message" />
<input type="submit" id="submit" onClick="this.value='Processing form';this.disabled=true;if(Submitting()){this.form.submit()}else{this.value='Submit';this.disabled=false;}" value="Submit" />
</form>

<form id="your-form">
<input type="submit" id="submit" onclick="doSubmit(this);" value="Submit" />
</form>
<script>
function doSubmit(el) {
var frm = document.getElementById('#your-form');
el.value = 'Processing...';
el.disabled = true;
frm.submit();
setTimeout(function(el) {
el.value = 'Submit';
el.disabled = false;
}, 5000);
}
</script>
This is one way to do it. There are several others.

You don't need to worry about this. If the user spams the form submit in any way (clicking submit or hitting enter), only one complete request is sent to the server - every time the submit is triggered, it resets the POST and starts again.
Do note that using JavaScript to stop this behaviour is pretty bad, considering it's incredibly easy to disable JS and spam away, which is one of the reasons why browsers only allow one POST submission at a time.
If you're using AJAX (which you haven't specified), then you should use #drrcknlsn's answer.

If your using Ajax you use the "Ajax Manager Plugin." It will prevent double requests.
That way you don't have to worry about a person hitting enter or the submit button multiple times. Only one request will go through until it is finished(but by then I would assume a success message and clearing of the form would happen)

Related

Javascript timeout problem with Flask backend [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

multiple form actions with one submit button

I want to ask about "multiple form actions with one submit button"
The form actions will be 2 places, Zoho CRM and Google form.
I have tested but the lead didn't save and can't go to thank you page.
I'm not sure if change to this script is correct or not:
function SubmitForm()
{
if(document.forms['leadform'].onsubmit())
{
showResultDiv();
document.forms['leadform'].action='https://crm.zoho.com/crm/WebToLeadForm';
document.forms['leadform'].submit();
document.forms['leadform'].action='https://docs.google.com/forms/d/e/1FAIpQLScQzsovLE8zusA88V7VTKQ5ACVYkbg0PWQmTsPd1NKGum8Tsw/formResponse';
document.forms['leadform'].submit();
}
return true;
}
The type of button is submit:
<input class="button" type="submit" value=">> Submit" onclick="javascript: return SubmitForm()">
I think the SubmitForm() will never be executed. the form has been submitted,and go to another page.
EDIT:
I guess that you are a freshman for web development. this page can help you know about <form> and <input type='submit'>

How can I keep focus on a overlay popup after submitting a form?

I have an overlay popup with a form inside. The form has a button and a textbox (imagine something like the FB Like and Comment box). Every interaction with the form triggers a MySQL DB Insert called through a PHP function. The problem is that after having clicked on the button or commented (and pressing enter key on the keyboard), the overlay disappears and the main page is refreshed. I don't want this to happen and I want to keep the focus on the popup. How can I do that?
Here's some code:
<div id="LikeAndComment">
<form name="formLAC" method="post" action="">
<div id="containerLike">
<button type="submit" id="likeit" value="FALSE" onClick="{vote(); keepFocus();}">
<img src="images/implike_BUTTON.jpg" "/>
</button>
</div>
<div id="containerComment">
Commenta: <input type="text" class="input" id="comment" onkeydown="if (event.keyCode == 13) { this.form.submit(); keepfocus(); return false; }"></input>
</div>
</form>
</div>
And here's the code of the keepFocus function:
function keepFocus() {
$('.formLAC').focus();
};
When you submit form as default without prevent form submit and using ajax, The browser will generate a new request and redirct you to the action url that you defined.
What you ask is to submit the form without redirect the page.
The ideal solution is to use ajax.
You can catch the submit-form event and prevent the default action.
then you have to handle it with you own code, In this case the ajax function.
An example how to send form with ajax you can see on this post with nice answer:
link to how make form submit with ajax

cancel form submission when a button is clicked

I have a login form. No doubt it accepts username / password. And I have 2 buttons, submit button and a cancel button.
What I want to do is when user clicks on submit button, login request starts processing. User can see the login screen for 8-10 seconds. When he clicks on cancel button that should allow him to cancel form submission (cancel login).
Please let me know how to do this. I know there can be a js function but I haven't encountered any. Thanks a lot in advance!
Have you tried :
function cancel () {
document.execCommand('Stop')
}
<input type = "button" name="cancel" value = "cancel" onclick = "cancel()" />
When user sends the login request, the request and authentication must be handled by some server side script like php. So, put a link on the cancel button to another server side script. This script should try to logout the user. If he has already logged in, he will log out so the cancel works. In other case, if he hasn't than nothing happens, the script ends doing nothing.
here is simple example with this you can create your own
html code
<form name="f1" action="test.jsp" method="get">
username:<input type="text" name="username">
password:<input type="password" name='password'>
<input id="sub" type="submit" name="subm" value="subm">
<input id="reset" type="button" name="reset" value="reset">
</form>
and jquery code
$(document).ready(function()
{
$('#sub').click(function(){
$('form [name="f1"]').submit();
});
$('#reset').click(function(){
$('input[name="username"]').val('');
$('input[name="password"]').val('');
});
});
this is just a reference and you can modify and create accordingly with your requirements
My suggestion:
"cancel" button is hidden at first.
When "login" button is clicked, send a login request, hide or disable "login" button, and show "canccel" button. then setup a default handler for normal login procedures:
$.post('login', params, function(){handler.loginCallback()});
When "cancel" button is clicked, replace the handler with another procedure:
handler.loginCallback = function() { ... }
If login failed, do nothing; If login succeeded, send another logout request.

How can I delay the submission of a form?

I have a web site that uses submit buttons to send commands to a remote microprocessor. If a user clicks the submit button too many times in a short amount of time, the remote microprocessor and software will crash. I thought I could add a one-second delay between each "submit" button press so it will not crash. Here is what I have for the submit button.
<form name="test" action="http://mydomain.dyndns.org/?8" target="results" method="POST">
<input type="submit" value=" ← Move Left " />
</form>
I thought I could use something like onSubmit="setTimeout (1000)" in the form, but it doesn't seem to be working. What am I doing wrong?
Example:
<form name="test" action="http://mydomain.dyndns.org/?8" target="results" method="POST" onSubmit="setTimeout (1000)">
<input type="submit" value=" ← Move Left " />
</form>
You'll have to actually write code to queue the requests and send them to the microprocessor at whatever rate the microprocessor can safely accept. You need to do this on the server side, not on the client side.
A back-end solution is preferable, but if you want to do it client-side as well (or instead):
If your onsubmit returns false it will stop submission.
I'd be inclined to solve this by:
Temporarily disabling the button for a second so that the user can't submit again quickly, and/or
Ignoring subsequent attempts to submit unless at least a second has passed.
I would not bother trying to queue up all the submissions and space them out, because the user could click the button lots of times.
So, the following ignores extra attempts to submit made within a second and disables the submit button. Why do both? If the form has fields in it the user could submit by pressing the Enter key.
<form name="test" action="http://mydomain.dyndns.org/?8" target="results"
method="POST" onSubmit="return testSubmit();">
<input id="submitButton" type="submit" value=" ← Move Left " />
</form>
<script>
var allowSubmit = true;
function testSubmit() {
if (!allowSubmit)
return false;
allowSubmit = false;
document.getElementById("submitButton").disabled = true;
setTimeout(function() {
allowSubmit = true;
document.getElementById("submitButton").disabled = false;
}, 1000);
return true;
}
</script>
Note this code: onSubmit="return testSubmit();" - you need the "return" in there or the value that comes back from testSubmit() is thrown away and submission will not be prevented.

Categories

Resources