jQuery / Bootstrap3: Disable/hide button after submit - javascript

I'm new to javascript, but I've searched extensively about this and tried dozens of different alternatives. Most of them did nothing at all, others prevented the form from submitting!
I have the following form:
<form name="buy" action="process_order.php" method="post">
<input type="hidden" name="itemid" value="{$itemid}">
<button type="submit" id="submit" name="submit" class="btn btn-sm btn-success">Buy</button>
</form>
I want to prevent double submissions by either disabling the submit button after submit or just make it disappear, whichever works best.
I have tried multiple JS approaches and I dont even know which one is best, so I wont provide one here to avoid confusion.
I'd be thankful if you could provide me a full javascript <script> snippet and anything else I eventually need. I would prefer to not use Ajax here, but let me know if that would help.
Many thanks!

You can use jQuery for this.
$('form[name="buy"]').on('submit', function() {
$('#submit').prop('disabled', true);
});
That will disable the submit button as soon as the form is submitted.
As #rolodex has pointed out submitting the form will refresh the page, thus the disabled button becomes enabled again. This is what I would do if not using Ajax (as #rolodex's answer does):
<form name="buy" action="process_order.php" method="post">
<input type="hidden" name="itemid" value="{$itemid}">
<button type="submit" id="submit" name="submit" class="btn btn-sm btn-success"<?php if(isset($_POST['itemid'])) echo ' disabled'; ?>>Buy</button>
</form>
Thus once someone has submitted the form, the button becomes disabled. This doesn't stop someone refreshing the page again without form data though, but neither does using Ajax. The only way to get around that would be to use cookies.

In order to prevent second submission after the first, you have to use AJAX, as far as I am concerned, because every time the form is submitted, the page will refresh and there will not be any indication if the form is already submitted or not. My approach here will use jQuery and here's how you do it.
First, remove the attribute action and method from your <form> which we will replace with the AJAX call. Just as simple as this;
<form name="buy">...</form>
Secondly, include the necessary jQuery library;
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Then the script;
<script>
$(function(){
$('form').on('submit', function(){
var data = $(this).serializeArray()
$.post('process_order.php', data, function(r,s){
console.log(r)
});
// Updated answer (change submit button's ID to class instead);
$(this).find('.submit').prop('disabled', true);
return false;
})
})
</script>
And that's all. It's identical to #Styphon's answer, but I believe that this is more complete and I hope this helps.
Cheers!

I use this (jQuery required):
<script>
var submiting = false;
$(function() {
$('form').submit(function() {
if (!submiting) {
submiting = true;
$('button[type=submit]').prop('disabled', true); //cosmetic
} else {
return false;
}
});
});
</script>
With this code, when the form is submitted, the boolean will prevent any further submission (ie. the user clicks really fast on the submit button) and will disable the button preventing further clicks.
But a much better aproach is described here:
Prevent double submission of forms in jQuery

Here is a neat solution
$('form').submit(function(){ //prevent multiple submit
$(':submit', this).click(function() {
console.log("submit prevented"); // Debug purpose.
return false;
});
});
If you submit form for instance 4 times, you will see the 3 "submit prevented" output.
$("#btn").trigger("click");
$("#btn").trigger("click");
$("#btn").trigger("click");
$("#btn").trigger("click");

Related

jQuery function not working on Form Submit

I saw from W3C example something like this. An action happens on form submit(an alert). However, when I tried with my own function here, my action doesn't happen (show hidden div). Goal is to show hidden div on form submit using 'GET' request. I am new to javascript/jQuery/ajax, but isn't jQuery supposed make call to server without refreshing page?
not working javascript:
$(document).ready(function(){
$("form").submit(function showDiv(){
document.getElementById("showMe").style.display = "block";
});
});
not working html:
<body>
<form action="" method="GET">
<input type="text" name="LastName" value="Mouse"><br>
<input type="submit" value="Submit">
</form>
<div id="showMe" style="display: none;">
<p>hey this should be hidden</p>
</div>
</body>
You need to cancel the form submit before executing your code:
$(document).ready(function(){
$("form").submit(function(e){
// At this point you'll want to have some type of flag to indicate whether you
// should allow the form submission to continue, or cancel the event. For example,
// it could be whether not showMe is visible (I don't know what you're going for).
e.preventDefault();
$("#showMe").css("display", "block");
// Submit form after your code runs (or whenever you want)
$("form").submit();
});
});
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault(); // this will prevent the submit
document.getElementById("showMe").style.display = "block";
});
});
Actually the jfiddle you posted is not blocking the form, it shows you an alert that block all js execution (browser behavior), if you select ok in the alert, the form goes through
the event.preventDefault() statement means: don't process anything outside this function
Try this:
$("form").submit(function(e){
e.preventDefault();
$("#showMe").show();
});
You need at least one form element (button or input), that has type "submit".
Then jQuery .submit() or .on('submit',..) will definitely work.

Making form's onsubmit to work only for particular submits

In PHP program, I have JS function which validates submit <form ...onsubmit='return isOK();'>. It works OK. The problem is I want it to work only for particular submits, not for all. Is there any way inside the JS function to find out which submit was pressed, or some PHP trick
instead of onsubmit u can use onClick.
<input type="submit" onclick="return pressSubmit1()" value="submit1" />
<input type="submit" onclick="return pressSubmit2()" value="submit2" />
<form action="action.php" method="post">
...
<input name="submit" type="button" value="check me" onclick="submitform('check')" />
<input name="submit" type="button" value="do not check me" onclick="submitform('not check')"/>
</form>
in javascript:
function submitform(check)
{
if(check=='check') checkfrom();
}
in PHP
if($_POST['submit']=="check me")
checkform();
<form class="allowed" onsubmit='return isOK();'>
----
function isOK() {
if($(this).hasClass('allowed')) {
// Do stuff
}
}
your question is not clear, are you using a single submit button or different ones. If you're using different submit buttons then ofcourse you can make checks based on the id of the submit button. On the other hand if is a single submit button then it depends on what the conditions are for submitting or not submitting
It's better you write some HTML and Java Script code which you are using. So, it's easy to correct mistake is you have made somewhere in code snippet.
We can check which submit button is clicked, using PHP.
In the PHP page corresponding to the form submit, write
if(extract($_POST) && isset($submitbtn1)) {
// some validation for first submit button
}
elseif(extract($_POST) && isset($submitbtn2)) {
// some validation for second submit button
}
Note: we can use $ followed by submit button name inside the extract function. ie. $submitbtn1 is same as $_POST['submitbtn1']
Yes different onclick looks fine as mentioned in the accepted answer. But in the event handler you should have the
code as below. Note the preventDefault.
Also since submit is A button that submits the form. You can use button type instead of submit type and then there is no need for preventDefault. Here is the link of the code http://jsbin.com/wikose/4/
function testlogin(){
event.preventDefault();
var test = 'not validated';
if(test === "validated")
alert("not valid login");
else
$('form').submit();
return false;
}

Disable submit button ONLY after submit

I have the following HTML and jquery:
<html dir="ltr" lang="en">
<head>
</head>
<body>
<h2>Test disabling submit button for 1 minute...</h2>
<br/>
<p style="text-align:center">
<form id="yourFormId" name="yourFormId" method="post" action="#">
<input type="submit" class="submitBtn" value="I Accept"/>
</form>
</p>
<!--script to disable the submit button -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".submitBtn").click(function () {
$(".submitBtn").attr("disabled", true);
return true;
});
});
</script>
<!--script ends here-->
</body>
</html>
As its stands the submit button gets disabled when pressed. However once pressed it does not seem perform the submit. If I removed the jquery to disable the button, the button then performs the submit normally.
How can I disable the button only after it has performed the submit? the current jquery above seems to conflict with the submit operation.
Any suggestions to resolve this issue would be extremely helpful.
Add the disable part in the submit event.
$(document).ready(function () {
$("#yourFormId").submit(function () {
$(".submitBtn").attr("disabled", true);
return true;
});
});
I faced the same problem. Customers could submit a form and then multiple e-mail addresses will receive a mail message. If the response of the page takes too long, sometimes the button was pushed twice or even more times..
I tried disable the button in the onsubmit handler, but the form wasn't submitted at all. Above solutions work probably fine, but for me it was a little bit too tricky, so I decided to try something else.
To the left side of the submit button, I placed a second button, which is not displayed and is disabled at start up:
<button disabled class="btn btn-primary" type=button id="btnverzenden2" style="display: none"><span class="glyphicon glyphicon-refresh"></span> Sending mail</button>
<button class="btn btn-primary" type=submit name=verzenden id="btnverzenden">Send</button>
In the onsubmit handler attached to the form, the 'real' submit is hidden and the 'fake' submit is shown with a message that the messages are being sent.
function checkinput // submit handler
{
..
...
$("#btnverzenden").hide(); <= real submit button will be hidden
$("#btnverzenden2").show(); <= fake submit button gets visible
...
..
}
This worked for us. I hope it will help you.
This solution has the advantages of working on mobile and being quite simple:
<form ... onsubmit="myButtonValue.disabled = true; return true;">
Hey this works,
$(function(){
$(".submitBtn").click(function () {
$(".submitBtn").attr("disabled", true);
$('#yourFormId').submit();
});
});
As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:
$("form.myform").submit(function (e) {
// Check if we have submitted before
if ( $("#submit-btn").attr('attempted') == 'true' ) {
//stop submitting the form because we have already clicked submit.
e.preventDefault();
}
else {
$("#submit-btn").attr("attempted", 'true');
}
});
Test with a setTimeout, that worked for me and I could submit my form, refers to this answer https://stackoverflow.com/a/779785/5510314
$(document).ready(function () {
$("#btnSubmit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$("#btnSubmit").prop('disabled', true);
}
});
Reading the comments, it seems that these solutions are not consistent across browsers.
Decided then to think how I would have done this 10 years ago before the advent of jQuery and event function binding.
So here is my retro hipster solution:
<script type="text/javascript">
var _formConfirm_submitted = false;
</script>
<form name="frmConfirm" onsubmit="if( _formConfirm_submitted == false ){ _formConfirm_submitted = true;return true }else{ alert('your request is being processed!'); return false; }" action="" method="GET">
<input type="submit" value="submit - but only once!"/>
</form>
The main point of difference is that I am relying on the ability to stop a form submitting through returning false on the submit handler, and I am using a global flag variable - which will make me go straight to hell!
But on the plus side, I cannot imagine any browser compatibility issues - hey, it would probably even work in Netscape!
This is the edited script, hope it helps,
<script type="text/javascript">
$(function(){
$("#yourFormId").on('submit', function(){
return false;
$(".submitBtn").attr("disabled",true); //disable the submit here
//send the form data via ajax which will not relaod the page and disable the submit button
$.ajax({
url : //your url to submit the form,
data : { $("#yourFormId").serializeArray() }, //your data to send here
type : 'POST',
success : function(resp){
alert(resp); //or whatever
},
error : function(resp){
}
});
})
});
</script>
I put this in my global code to work on all submit buttons:
$("input[type='submit']").on("click", function (e) {
$(this).attr("disabled", true);
$(this).closest("form").submit()
});
My problem was solved when i add bind section to my script file.
Totally i did this 2 steps :
1 - Disable button and prevent double submitting :
$('form').submit(function () {
$(this).find(':submit').attr('disabled', 'disabled');
});
2 - Enable submit button if validation error occurred :
$("form").bind("invalid-form.validate", function () {
$(this).find(':submit').prop('disabled', false);
});
Not that I recommend placing JavaScript directly into HTML, but this works in modern browsers (not IE11) to disable all submit buttons after a form submits:
<form onsubmit="this.querySelectorAll('[type=submit]').forEach(b => b.disabled = true)">
I went through a lot of solutions for my problem statement and I think most of the people here are also answering the same.
Generally, when you do a server side form submit, there is a chance of user clicking the button multiple times which leads to multiple submissions. So, to prevent that, the button should be disabled after the first submit. This is what worked for me in the most elegant way.
We have a form submit event <form onsubmit="onFormSubmitted()"></form>.
In onFormSubmitted() disable your submit button or do any operations required.
Handing this way retains your html validations as well as it disables the button once the form submit is triggered when first click of button takes place.
function onSubmit() {
$('.btn_submit').attr('disabled', true);
}
<form class="contact_form" method="POST" autocomplete="off" onsubmit="onSubmit()">
<input name="email" id="email">
<button class="btn_submit" type="submit">Submit</button>
</form>
Alternatively, you can also make global form submit handler for forms throughout the project.
$('form').on('submit', function() {
$(this).find(":submit").prop('disabled', true);
});
$(document).ready(function() {
$(body).submit(function () {
var btn = $(this).find("input[type=submit]:focus");
if($(btn).prop("id") == "YourButtonID")
$(btn).attr("disabled", "true");
});
}
$(function(){
$("input[type='submit']").click(function () {
$(this).attr("disabled", true);
});
});
thant's it.

Form fields value get reset without page load

Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.

How can I use Javascript to disable a button after submitting a form in Chrome?

I have a web form for which I want to prevent multiple submissions. In production, this is accomplished by the submit button having an onclick="this.disabled=true" attribute. This way, if the form is submitted and then the user goes back (presumably to "edit" the data, which our users seemed to want to do from time to time), the submit button remains disabled.
This works fine in Firefox, Safari, and Internet Explorer. In Chrome, however, the disable seems to fire before the form submission, thus preventing it from happening. In order to work around this, I changed the button's onclick action to:
this.disabled=true; $('myform').submit()
This results in the form being submitted, but when I use Chrome's back button to return to the form page, the button is no longer disabled. Values I entered into the form before submitting remain, so my guess is that Chrome must be selectively reloading the DOM.
Is there any way to accomplish what I want with Javascript in Chrome? There are other ways to solve this problem, of course, but disabling the button has a highly attractive simplicity to it.
I've tested in Chrome 12.0.742.100 in Linux, and 12.0.742.112 in MacOS X.
I prefer this
http://jsfiddle.net/mplungjan/sCgZ9/
Script:
$("form").submit(function() {
$("#subbut").hide();
$("#submitted").show();
});
CSS:
#submitted { display:none }
HTML:
<form action="http://www.google.com/" target="_blank">
<input type="submit" id="subbut" /><span id="submitted">Form submitted</span>
</form>
You can set a cookie if you want to decide to show or not show the button
Consider instead using the form's submit to disable the button.
In any case, you sould be dealing with this at the server, there are other ways to submit a form without using the submit button. Disabling the button will not prevent the user from re-submitting the form.
Using javascript
<form name ="myform" method="POST" action="youractionhere" onSubmit="document.getElementById('submit').disabled=true;">
<input type="submit" name="submit" value="Submit" id="Submit">
</form>
Using jQuery
$("form").each(function() {
$(this).find("button:submit").click(function() {
if($('input[type="submit"]').hasClass("disabled"))
return false;
$('input[type="submit"]').addClass("disabled");
return true;
});
});
I use to do this
html
<form action="/" method="post">
<button type="button" class="submit-form" >Save</button>
</form>
javascript
var button = document.querySelector('.submit-form')
button.addEventListener("click", function(){
this.setAttribute('disabled',true);
var form = this.closest('form')
form.submit();
},false);
jquery
$(document).on("click",".submit-form",function(){
$(this).attr('disabled',true);
$form = $(this).closest('form');
$form.submit();
});

Categories