I've been trying to find the "right" way to prevent double submits of forms. There are lots of related posts on SO but none of them hit the spot for me. Two questions below.
Here is my form
<form method="POST">
<input type="text" name="q"/>
<button class="once-only">Send</button>
</form>
Here is my first attempt to disable double submits:
$(document).ready(function(){
$(".once-only").click(function(){
this.disabled = true;
return true;
});
});
This is the approach suggested here: Disable button after post using JS/Jquery. That post suggests the submitting element must be an input rather than a button, but testing both makes no difference. You can try it yourself using this fiddle: http://jsfiddle.net/uT3hP/
As you can see, this disables the button, but also prevents submission of the form. In cases where the submitting element is a button and an input element.
Question 1: why does this click handler stop submission of the form?
Searching around some more I find this solution (from Why doesn't my form post when I disable the submit button to prevent double clicking?)
if($.data(this, 'clicked')){
return false;
} else{
$.data(this, 'clicked', true);
return true;
}
You can play with this using this fiddle: http://jsfiddle.net/uT3hP/1/
This does work, but...
Question 2: Is this the best we can do?
I thought this would be an elementary thing. Approach 1 does not work, approach 2 does, but I don't like it and sense there must be a simpler way.
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
You can use jQuery's submit(). In this case, it should look something like this:
$('form').submit(function(){
$(this).children('input[type=submit]').prop('disabled', true);
});
Here is a working jsFiddle (made by Mike) - http://jsfiddle.net/gKFLG/1/.
If your submit-button is not a direct child of the form-element you will need to replace children with find. Additionally, your submit-button may also be a button element instead of an input element. E.g. This is the case if you are using Bootstrap horizontal forms. Below is a different version of the snippet:
$('form').submit(function(){
$(this).find('button[type=submit]').prop('disabled', true);
});
Demo jsFiddle - http://jsfiddle.net/devillers/fr7gmbcy/
Similarly Ive seen a few examples, this one allows you to alter how long the button is disabled for, through timeout. It also only triggers on a form submit rather than on the buttons click event, which originally caused me a few issues.
$('form').submit(function () {
var button = $('#button');
var oldValue = button.value;
var isDisabled = true;
button.attr('disabled', isDisabled);
setTimeout(function () {
button.value = oldValue;
button.attr('disabled', !isDisabled);
}, 3000)
});
You could try using the following code:
$(document).ready(function(){
$(".once-only").click(function(){
this.submit();
this.disabled = true;
return true;
});
});
This should help:
<form class="form-once-only" method="POST">
<input type="text" name="q"/>
<button type="submit" class="once-only">Send</button>
</form>
Javascript:
$(document).ready(function(){
$("form.form-once-only").submit(function () {
$(this).find(':button').prop('disabled', true);
});
}
Related
I am trying to replicate the review post feature you see here on stackoverflow, I am struggling with the requiring two clicks to submit portion of this though. My searches have returned multiple problems with validate but nothing quite pertaining to what I am looking for.
I have a standard form:
<form action="http://www.google.com/">
<textarea name="text"></textarea>
<input type="submit" name="review" value="Review" />
</form>
With the following jQuery:
$(function(){
$('form').submit(function(){
$('html, body').animate({scrollTop : $(".Anchor").offset().top}, 300);
return false; // to cancel form action
});
});
How can I make it so when the submit is pressed it goes to the anchor, then the next time it is pressed it submits the form? I would like to change the value from review to submit also, but I'm sure I can figure that part out after receiving a reply to the initial question.
A live sample of what I have can be found here on CodePen
By Using a variable within your function, you can toggle the variable from true to false upon click. With this method you can manipulate anything you want the second action to be within an else statement.
An example of this based on the code you provided:
$(function(){
let hasUserReviewedTheForm = false;
$('form').submit(function(){
if(!hasUserReviewedTheForm) {
$('html, body').animate({scrollTop : $(".Anchor").offset().top}, 300);
//change the form name and change the variable value
hasUserReviewedTheForm = true;
return false; // to cancel form action
}
else {
//Submit the form
}
});
});
I am absolutly new in JQuery development and I have the following problem.
I have a form that contains this JQuery button:
<!-- RESET BUTTON: -->
<td>
<button class="resetButton" name="submitReset" onclick="return resetSearch(); return false;">Reset</button>
</td>
Clicking this button the user reset to null two input that are into my form performing this JavaScript function:
function resetSearch() {
var f = document.getElementById('dataDaAForm');
f.dataDa.value = null;
f.dataA.value = null;
event.preventDefault();
}
The script is performed but the problem is that after that it go out from the previous function the form is submitted anyway and I don't want that this behavior happen.
How can I prevent that the form is submitted when the user click on the reset button? As you can see I also try to add this statment but it don't work:
event.preventDefault();
What am I missing? How can I fix this issue?
Another question is: is it the correct way to reset the values of the input tag of my form?
Give this a shot - you need to pass the event into the function. In addition, I've removed the need for inline JS.
$(".resetButton").click(function(e) {
var f = document.getElementById('dataDaAForm');
f.dataDa.value = null;
f.dataA.value = null;
e.preventDefault();
});
In addition to preventing the default, Javascript provides a method to reset your form:
$(".resetButton").click(function(e) {
document.getElementById("dataDaAForm").reset();
e.preventDefault();
});
Note: You tagged jquery, so I provided a jquery solution (although there is no jquery in your question).
The simplest way to create a reset button is an input type reset:
<input type="reset" value="Reset" />
Though if you really want to do it in javascript, the answer of James Hill will suffice
Try this
var form = $('#dataDaAForm')
$(".resetButton").on("click",function(e) {
form.reset()
e.preventDefault()
e.stopPropagation()
})
<input type="submit" name="btnADD" id="btnADD" value="ADD"/>
when user click add button twice, from get submitted twice with same data into table.
So Please help me to restrict user to submit from twice.
Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:
var $myForm = $("#my_form");
$myForm.submit(function(){
$myForm.submit(function(){
return false;
});
});
Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.
try out this code..
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />
You can disable the button after clicking or hide it.
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>
js :
function disableButton(button) {
button.disabled = true;
button.value = "submitting...."
button.form.submit();
}
If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.
http://www.xinotes.org/notes/note/369/
A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.
And if you are not using any framework and looking for simple workout.
You can take help of the
java.util.UUID.randomUUID();
Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.
For your help i am writing some code snippet to give idea about how to achieve the thing.
<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>
You could notify the user that he drinks too much coffee but the best is to disabled the button with javascript, for example like so:
$("#btnADD").on('click', function(btn) {
btn.disabled = true;
});
I made a solution based on rogueleaderr's answer:
jQuery('form').submit(function(){
jQuery(this).unbind('submit'); // unbind this submit handler first and ...
jQuery(this).submit(function(){ // added the new submit handler (that does nothing)
return false;
});
console.log('submitting form'); // only for testing purposes
});
My solution for a similar issue was to create a separate, hidden, submit button. It works like so:
You click the first, visible button.
The first button is disabled.
The onclick causes the second submit button to be pressed.
The form is submitted.
<input type="submit" value="Email" onclick="this.disabled=true; this.value='Emailing...'; document.getElementById('submit-button').click();">
<input type="submit" id='submit-button' value="Email" name="btnSubmitSendCertificate" style='display:none;'>
I went this route just for clarity for others working on the code. There are other solutions that may be subjectively better.
You can use JavaScript.
Attach form.submit.disabled = true; to the onsubmit event of the form.
A savvy user can circumvent it, but it should prevent 99% of users from submitting twice.
You can display successful message using a pop up with OK button when click OK redirect to somewhere else
Disable the Submit Button
$('#btnADD').attr('disabled','disabled');
or
$('#btnADD').attr('disabled','true');
When user click on submit button disable that button.
<form onSubmit="disable()"></form>
function disable()
{
document.getElementById('submitBtn').disabled = true;
//SUBMIT HERE
}
Create a class for the form, in my case I used: _submitlock
$(document).ready(function () {
$(document).on('submit', '._submitlock', function (event) {
// Check if the form has already been submitted
if (!$(this).hasClass('_submitted')) {
// Mark the form as submitted
$(this).addClass('_submitted');
// Update the attributes of the submit buttons
$(this).find('[type="submit"]').attr('disabled', 'disabled');
// Add classes required to visually change the state of the button
$(this).find('[type="submit"]').addClass("buttoninactive");
$(this).find('[type="submit"]').removeClass("buttonactive");
} else {
// Prevent the submit from occurring.
event.preventDefault();
}
});});
Put a class on all your buttons type="submit" like for example "button-disable-onsubmit" and use jQuery script like the following:
$(function(){
$(".button-disable-onsubmit").click(function(){
$(this).attr("disabled", "disabled");
$(this).closest("form").submit();
});
});
Remember to keep this code on a generic javascript file so you can use it in many pages. Like this, it becomes an elegant and easy-to-reuse solution.
Additionally you can even add another line to change the text value as well:
$(this).val("Sending, please wait.");
Add a class to the form when submitted, stopping a user double clicking/submitting
$('form[method=post]').each(function(){
$(this).submit(function(form_submission) {
if($(form_submission.target).attr('data-submitted')){
form_submission.preventDefault();
}else{
$(form_submission.target).attr('data-submitted', true);
}
});
});
You can add a class to your form and your submit button and use jquery:
$(function() {
// prevent the submit button to be pressed twice
$(".createForm").submit(function() {
$(this).find('.submit').attr('disabled', true);
$(this).find('.submit').text('Sending, please wait...');
});
})
None of these solutions worked for me as my form is a chat and repeated submits are also required. However I'm surprised this simple solution wasn't offered here which will work in all cases.
var sending = 0;
$('#myForm').submit(function(){
if (sending == 0){
sending++;
// SUBMIT FORM
}else{
return false;
}
setTimeout(function(){sending = 0;},1000); //RESET SENDING TO 0 AFTER ONE SECOND
}
This only allows one submit in any one second interval.
I know there are a lot of questions about it, but I tried several solutions, and nothing works.
In my django app I have a form:
<form method='post'>
<button type='submit'>Send</button>
</form>
I wan't to disable the button once the user has submitted the form. Using other questions, I tried several things, like:
<button type='submit' onclick="this.disabled=true">Send</button>
When I click, the button is disabled... but the form is not submitted. And for each try I had the same issue: either the button is disabled or the form is submitted. I can't find how to do both...
I'm using Chrome. Any idea on why I have this problem? Thank you for your help.
Try this:
$('form').submit(function() {
$(this).find("button[type='submit']").prop('disabled',true);
});
I like this, don't have to traverse the DOM.
Put function on a setTimeout function, this allows make submit and after disable button, even if setTimeout is 0
$(document).ready(function () {
$("#btnSubmit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$("#btnSubmit").prop('disabled', true);
}
});
You could disable it upon the parent form's submit event:
$("form").on("submit", function () {
$(this).find(":submit").prop("disabled", true);
});
Be sure to run this code only after the HTMLFormElement has been loaded, or else nothing will be bound to it. To ensure that the binding takes place, fire this off from within a document-ready block:
// When the document is ready, call setup
$(document).ready(setup);
function setup () {
$("form").on("submit", function () {
$(this).find(":submit").prop("disabled", true);
});
}
Something like this might work.
<button id="btnSubmit" type='submit'> Send </button>
<script>
$("#btnSubmit").on("click", function(e){
e.PreventDefault();
$(this).closest("form")[0].submit();
$(this).prop('disabled',true)
});
</script>
Try, like this,
<input type="submit" value="Send" onclick="javascript=this.disabled = true; form.submit();">
This ended up being the best solution for me
$("form").submit(function disableSubmit() {
$("input[type=submit]", this).prop("disabled", true);
});
my variant, disable button, no direct disabled but only vidible hidden:
<input type="submit" name="namebutton" value="Nahrát obrázek" onclick="this.style.visibility='hidden';" ondblclick="this.style.visibility='hidden';"/>
You can do something like this. It is work fine with me.
<form method='post' onSubmit='disableFunction()'>
// your code here
</form>
Then in script, add this
<script>
function disableFunction() {
$('#btn_submit').prop('disabled', true);
}
</script>
How about this?
onclick="this.style.visibility='hidden';"
I would say, instead of disabled, hide it.
If you want to go with disabled
onclick="this.style.disabled='true';"
Got an issue on Chrome, wasn't submitting the form. Tried a bunch of different code, this was what worked best for me (and looks best imo):
$('#form_id').submit(function() {
$("input[type='submit']", this)
.val("Please Wait...")
.attr('disabled', 'disabled');
return true;
});
Replace form_id with the id of your form. Classes work too of course: $('.form_class')
Source: JavaScript Coder
I like this better:
<script>
var submit = false;
$('form').submit(function () {
if (submit) { return false; }
else { submit = true;}
});
</script>
this way it also prevents the enter key to submit more than once
I'm using Chrome. Any idea on why I have this problem?
Well, first time I dealt with this, I solved it like this:
function blockButtons() {
$('button:submit').click(function(){
$('button:submit').attr("disabled", true);
});
}
This worked perfectly, but... in Mozilla Firefox. The Google Chrome did not submit it, so I changed it to this:
function blockButtons() {
$('button:submit').click(function(){
var form = $(this).parents('form:first');
$('button:submit').attr("disabled", true);
$('button:submit').css('opacity', 0.5);
form.submit();
});
}
This worked both in Mozilla Firefox, however, after that some of our users using old versions of IE experienced trouble of having two submits. That is, the one initiated by the javascript, and the one by browser ignoring the fact of onclick and just submitting anyway. This can be fixed by e.preventDefault, I guess.
If you don't want an element to be double-clicked, use .one()
<button id="submit" type="submit">Send</button>
<script>
$(function () {
$("#submit").one("click", function () {
//enter your submit code
});
});
.one()
You can do something like this. It is work fine with me.
$("button#submitted").click(function () {
$("button#submitted").prop('disabled', true);
});
Double click on your button. This code will running
You must prevent the form from being submitted more than once, disabling the button is not the right solution because the form could be submitted in other ways.
JavaScript:
$('form').submit(function(e) {
// if the form is disabled don't allow submit
if ($(this).hasClass('disabled')) {
e.preventDefault();
return;
}
$(this).addClass('disabled');
});
Once the form is correctly disabled, you can customize its appearance.
CSS:
form.disabled {
pointer-events: none;
opacity: 0.7;
}
I have a button that saves the content that a user edits. I do not want them to hit the save button multiple times because of the load it causes on the server. I want to disable the button after they click on it.
Here is what I have attempted(doesn't work, though):
var active = true;
$("#save").click(function() {
if (!active) return;
active = false;
........
........
........
active = true;
The problem is that the user can still click on the element multiple times.
How can I fix this problem?
Edit: Sorry, I forgot to mention that I want to enable the click after the onclick code has finished executing.
Try this
$("#save").one('click', function() {
//this function will be called only once even after clicking multiple times
});
There is a disabled attribute: http://jsfiddle.net/uM9Md/.
$("#save").click(function() {
$(this).attr('disabled', true)
........
........
........
$(this).attr('disabled', false)
});
You can unbind the click handler, but I would go with .one as per #ShankarSangoli's answer (+1).
$("#save").click(function() {
// do things
$(this).unbind("click");
});
http://api.jquery.com/unbind/
If the element is an input you can do this really easily:
<input name="BUTTON" type="submit" value="Submit" onSubmit="document.BUTTON.disabled = true;">
That's some handy HTML Javascript integration stuff there.
Assuming:
<input type="button" id="save" ... />
You can either do:
$('#save').click(function(){
var $save = $(this);
//
// save code
//
$save.get(0).disabled = true;
});
Which disabled the button natively, or you can use jQuery's one functionality:
$('#save').one('click',function(){
//
// save code
//
});
Which will only execute once and must be re-bound. (But if you're deciding to enable/disable based on parameters, using the disabled attribute is probably a better choice.)