I have a short form, you can see it here http://jsfiddle.net/azxpckg5/1/
and I have a problem - the way to reproduce it is to click the save button. Then there will appear another button called submit. when user clicks it - it disappears and it's fine. But when user repeats this procedure (clicks save again and submit again - he can see that the last click was repeated twice. I believe the error might be somewhere here:
submitHandler: function (form) {
alert("here!");
$(".overlay-boxify2").toggleClass("open");
$('#submitcForm').click(function() {
//
$(".overlay-boxify2").toggleClass("open");
alert("hegdsgsd");
});
return false;
}
but to be honest I don't know how to fix it and what can be the issue. Can you help me with that?
The issue is because you're attaching another click event handler to the #submitcForm button on every submission of the form (which happens when #saveBtn is clicked. Move the click handler outside of the validate() call and your code will work as you require.
$('#invoiceForm').validate({
// settings...
});
$('#submitcForm').click(function () {
$(".overlay-boxify2").toggleClass("open");
});
Updated fiddle
Use .off() to prevent attaching multiple click eventListener on your button
submitHandler: function (form) {
alert("here!");
$(".overlay-boxify2").toggleClass("open");
$('#submitcForm').off().click(function() { // see the use of .off()
$(".overlay-boxify2").toggleClass("open");
alert("hegdsgsd");
});
return false;
}
See more about .off()
I want to prevent multiple form submissions, but I need to have the value of the submit element posted back to the server (so that I know which button the user clicked on).
Most of the Internet Wisdom concerning suppression of multiple form submissions seems to involve disabling the submit button during form submission. This prevents the button from being clicked a second time, but also prevents its value from being posted.
I've found a few examples of JS code that hides the submit button(s), which allows their values to be posted. But those examples all replace the (now hidden) button with some sort of "processing..." message. I really want a solution that presents the user with a disabled button but still posts the button value.
I should add that I'd prefer a solution that works with standard HTML one would find in most forms. No magic IFrames, hidden fields, id or class names, etc. I want a JS function I can stash away in a library and reference from all of my existing forms to enable this new behavior.
(I have a solution, which I will post as an answer. But I had to ask the question to comply with the Zen of SO.)
Here is (yet another) answer to the question of how to deal with preventing the user from clicking on the form submission button more than once. This solution makes it appear that the button has been disabled.
Under the covers, it creates a disabled button to display to the user, and hides the actual button so that its value is posted. I also move the hidden button so that the extra element doesn't mess up CSS selectors.
Also note the check for invalid form fields. If you omit this check, and form validation fails, then the user winds up with a form that wasn't posted (because client-side validation failed) but the buttons are disabled.
// Disables buttons when form is submitted
$('form').submit(function () {
// Bail out if the form contains validation errors
if ($.validator && !$(this).valid()) return;
var form = $(this);
$(this).find('input[type="submit"], button[type="submit"]').each(function (index) {
// Create a disabled clone of the submit button
$(this).clone(false).removeAttr('id').prop('disabled', true).insertBefore($(this));
// Hide the actual submit button and move it to the beginning of the form
$(this).hide();
form.prepend($(this));
});
});
Because you can submit a form other ways than simply clicking the submit button it's better to add a listener to the form's submit event rather than the click event on the submit button. This jQuery event listener should work on any form and prevent it from being submitted more than once.
$('form').on('submit', function(e) {
if (!$(this).data('submitted')) {
$(this).data('submitted', true);
}
else {
e.preventDefault();
}
});
To make the form look disabled you could add some css that makes the form look disabled and then add the classname on form submission.
$('form').on('submit', function(e) {
if (!$(this).data('submitted')) {
$(this).data('submitted', true).addClass('disabled');
}
else {
e.preventDefault();
}
});
I wanted to stop the user from causing multiple form submissions by double clicking the submit button or hitting the enter key twice. I like this solution, because it doesn't require a hidden form field or hiding the submit button.
The two key points are:
Return true/false instead of using e.preventDefault() and form.submit(), because form.submit() doesn't know which button was clicked and therefore, can't pass the button name/value.
Disable the button with pointer-events: none; instead of disabled="disabled", because the disabled attribute won't send the button name/value. I believe pointer-events: none; is not supported by Internet Explorer 10 or below.
javascript/jquery code:
var form_selector = 'form',
button_selector = 'button, input[type=submit], input[type=button], input[type=reset]',
deactivated_classname = 'state-submitting',
deactivated_class = '.'+'state-submitting';
// Capture the submit event so it will handle both the
// enter key and clicking the submit button.
$(document).on('submit', form_selector, function(e) {
var form = e.target,
buttons = $( form ).find( button_selector );
// Returns, because the form is already being submitted by a previous attempt.
if( $( form ).find( deactivated_class ).length > 0 ) return false;
disableButtons( buttons );
// Safari (version 11) bugfix: Safari needs a timeout or it won't
// show the deactivated styles.
setTimeout(function() {
// Must use return true, because using form.submit(), won't pass the button value.
return true;
}, 50 );
});
function disableButtons( buttons ) {
// Disables all buttons in the form.
$( buttons ).each(function( index, elem ) {
$( elem ).addClass( deactivated_classname );
});
}
For AJAX forms, you will want to re-enable the buttons after the response is returned.
$( document ).on( 'ajax:complete', form_selector, function(e) {
var form = e.target,
buttons = $( form ).find( button_selector );
enableButtons( buttons );
});
function enableButtons( buttons ) {
$( buttons ).each(function( index, elem ) {
$( elem ).removeClass( deactivated_classname );
});
}
CSS:
// The button is disabled while it is submitting.
.state-submitting {
// Turns off hover and click events. Not supported in IE 10 and below.
pointer-events: none;
opacity: 0.5;
}
You can simulate disabled look behavior. E.g. if you have a button like this:
<input id="btn" type="button" onclick="disableMe(this)" value="Submit" />
You can define CSS like this
.disabled {
backround-color:grey;
color:darkgrey;
}
And JS like this
function disableMe(btn) {
btn.className = "disabled";
btn.onclick = function(){return false}
}
What will happen - on first click button will become grey (via applied CSS) and onclick event will change to "return false" for all the consecutive calls preventing future click actions. The button will appear and act as disabled, but will not be, so it will not prevent button submission.
Here's a couple options:
1. You could create hidden inputs and dynamically change the value of it before the form is submitted either onClick or onHover of the said button:
2. You could create an hidden iframe which is the target of the said form. Once the submit button is click, you could cancel the submit event, grab all of the data and send it programatically through the iframe instead.
I was having the same issue as OP, and I found that disabling the submit button(s) after a short (maybe 0 seconds) timeout via setTimeout does the trick. The submit button's name value is still posted with the rest of the form data as desired, but the button disables itself (almost) immediately, preventing further clicks.
The timeout is a bit ugly, but it seems preferable to more elaborate swapping/covering schemes.
This could be combined with also altering the form's onsubmit property for extra precaution, but I'm not doing that in the example below for clarity's sake. Either way, I like the appearance/behavior of a disabled button after the first submission click… the user experience seems better to me… it's more clear what's happening.
My form element's start tag:
<form onsubmit="return formSubmit(this);" method="post" action="">
In my JavaScript (sorry, I'm not up-to-date with the latest JS tech like jQuery, etc, so I'm posting this in old-fashioned-native-JavaScript-5-with-no-dependencies-compatible code):
function formSubmit(form) {
// MUST DELAY so as not to break input/button[type=submit] name submission
setTimeout(function () {
var els = form.elements;
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.getAttribute('type') == 'submit') {
el.setAttribute('disabled', 'disabled');
}
}
}, 0);
return true;
}
I think better solution would be to use JQuery :
<form onsubmit="$('#submit').hide();" method="post" action="">
No chance of double clicking.
Sometimes we use name field in submit button for validation so if this is disabled then that could failed.
Using .hide() the button will be hidden.
so no chance of double clicking it.
Be honest with you I was not able to understand fully most of the posts on this page, but I think I have faced this problem before, and solved it by allowing the page to post the first time the button is clicked, so when the page comes back from server it has the new value assigned to it, and it looks clickable, and enabled. But if a 2nd attempt is made to press it, then it becomes disabled, and page will not post, and send to the server again by clicking this button. I hope this helps:
#section scripts
{
<script type="text/javascript">
$('#edit').click(function () {
if (document.getElementById("edit").value == '') {
// This portion should execute onlythe
// first time button is clicked, and it
// will assign a new value to the button,
//and posts the value
//to the server
}
else {
edit.disabled = true;
}
});
</script>
}
A much much much simpler way is to enclose whatever code you use to disable the button in a setTimeout() with 0 delay. That way the button is still enabled in the thread that handles the form submission while another parallel thread is spawned to do the disabling.
Example (using jQuery):
<form method="POST" onsubmit="javascript:setTimeout(() => $('*[type=submit]', this).attr('disabled', 'disabled'), 0)">
I have an form with dropdown. whenever i select the drop down once i click save itself it appear it do some action. I want to as auto save when you change the dropdown values.
Here is the fiddle:
http://jsfiddle.net/GGtTw/
jQuery('select[name="dropdown"]').change(function() {
alert(jQuery(this).val());
});
jQuery('#submit').click(function() {
alert('you click submit button');
});
I want once you select the dropdown it automatically submit the values means it automatically click save without noticing to the user.
Any suggestion would be great.
Thanks
Use trigger to simulate a click event for the given object
jQuery('select[name="dropdown"]').change(function() {
jQuery('#submit').trigger('click');
});
jQuery('#submit').click(function() {
alert('you click submit button');
});
just do
$( "#submit" ).trigger( "click" );
Another Approach:
jQuery('select[name="dropdown"]').change(function() {
save();
});
jQuery('#submit').click(function() {
save();
});
function save()
{
alert('Save');
}
Make an ajax call to save from inside your drop down change event. Unless you want to perform a form submit, in that case trigger the click function on the submit like so
jQuery('#submit').trigger('click');
jQuery ajax()
I must rebuild a form, there are two buttons, one is for increasing the value of an input and second for decrease the value, and I must delete submit button and update form always if I click on increase or decrease, i have tried this with jquery onchange:
I have read also this: http://api.jquery.com/submit/
$("#increaseButton").change( function() {
$("#quantityForm").submit();
});
I can't edit form, because I must work only with submit, is that possible?
I think a click would be better here:
$('#increaseButton').on('click', function() {
increaseValue(); //call a function to increase the value
$("#quantityForm").submit(); //submits the form
});
what is #increaseButton? is it just a link? or actual
<input type="button" />
I don't think buttons can have a "change" event attached to them
I have this issue that when user clicks a button (in this case, a submit button) multiple times, jQuery will keep playing the animation effects until it has completed the count of clicks the user has imputed.
This can get quite overwhelming.
How can jQuery tell if it's currently executing an animation to a particular element, so I can prevent user from submitting while the elements effect is still in play?
Notes: the submit button is in a file. Form handling is relayed via AJAX this jQuery is inside the ajax called file.
Here is the main files code:
$('#login_form').submit(function(e) {
$.post(
"ajax.php",
{ user: $('[name="username"]').val(), pw: $('[name="password"]').val() },
function(resposeText) { $('#login_form_response').html(resposeText); },
"html"
);
e.preventDefault();
});
Here is the code (in ajax'ed' file):
$('#login_form_response').html('Username or Password is inaccurate!')
.slideDown()
.delay(3500)
.slideUp(1500);
You could unbind the event-handler just before starting the animation, and in the callback function of the animation, just bind the handler again.
$('#button').unbind('click');
$('#animated_element').animate({ animation, stuff}, 1000, function(){
$('#button').bind('click', handlerFunc);
});
Note:
This is a way to prevent submitting when you are using a customized button (div, or a link), which has an event handler binded to it. It does not work on pure html <input type="submit" /> - buttons, because after unbinding, the standard-submit is going to take effect.
I prefer to use customized buttons, mainly because of styling (especially for IE7 and such).
If you want to use a pure html-submit button, you'll have to disable the button (and disabling submit over "enter") or set a flag, that prevents submitting, as other users have already stated in their answers!
Disable the submit button until the animation finishes.
$('animatingElementSelector').animate({height: 200px;}, slow, function() { //ENABLE BUTTON HERE });
var isAnimationRunning;
jQuery('#myForm').bind('submit',function(e){
if(isAnimationRunning)
{
e.preventDefault();
}
});
Create a variable isAnimationRunning let it know, animation running or not. If running then ignore submit.
http://jsfiddle.net/praveen_prasad/cfvRf/
On demo click start animation and then try to submit!!
Edit 1
Some ppl have suggested unbinding click of submit button, that wont work. If a submit button is inside a form, clicking it will submit the form, you dont bind click event to submit form, its just pure html, so unbinding wont help in stopping submit event. check this demo
Edit 2
Some ppl have suggested disable the submit button during the animation. That wont always work either, consider a situation where user types something in text box and press enter key, form will be submitted(some browsers will) regardless of submit button being disabled.
Just add disabling button when it clicked :) or hide... or both of this... hide and disable
Try this:
$('#login_form').submit(function(e) {
$('input[type=submit]', this).attr('disabled', 'disabled').attr('style','opacity: 0.5; filter: alpha(opacity = 50); ');
$.post(
"ajax.php",
{ user: $('[name="username"]').val(), pw: $('[name="password"]').val() },
function(resposeText) { $('#login_form_response').html(resposeText); },
"html"
);
e.preventDefault();
});