jQuery form getting submitted multiple times - javascript

I've made a simple lightbox implementation in my code. By Clicking on #makePayment link a lightbox is opened, and within that lightbox there is a form. When user clicks on #paymentDetailsConfrimLB to submit the form, I've just displayed an alert.
Before I explain the problem, please have a look at the code I've written:
$("#makePayment").click(function() {
$("body").addClass("modalPrint");
var lb = new LightBox("paymentDetailsLB", "675", "500");
lb.htmlObjRef.style.height = "auto";
lb.show();
$("#paymentDetailsCloseLB, .hideBox").click(function() {
$("body").removeClass("modalPrint");
lb.hide();
});//paymentDetailsCloseLB
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
return false;
});//makePayment
Problem is, when I first load the page, and open the lightbox, and click the submit button, the alert is shown once (as it should), but if I close the lightbox, re-open it, and then submit the form, it is submitted twice and alert is shown twice. Similarly if I again close and re-open the lightbox, upon form submission the alert shows up 3 times, and it goes on like this.
Any idea on how I can resolve this?

Other than Kavin's approach, another solution also worked for me. I just added this line immediately after the event.preventDefault() method:
event.stopImmediatePropagation()
And it resolved the issue.

You're setting click callback every time you open lightbox. Try to move click callbacks out of #makePayment:
$("#makePayment").click(function() {
$("body").addClass("modalPrint");
var lb = new LightBox("paymentDetailsLB", "675", "500");
lb.htmlObjRef.style.height = "auto";
lb.show();
return false;
});//makePayment
$("#paymentDetailsCloseLB, .hideBox").click(function() {
$("body").removeClass("modalPrint");
lb.hide();
});//paymentDetailsCloseLB
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB

You're binding a new handlers every time the submit button is clicked. You only need to define a handler once, and it will be executed whenever that action occurs. Otherwise, each handler you bind will execute.
If you absolutely needed to bind the handlers the way you are, then you could also use .one, which will only bind the handler the first time for each element.
jQuery .one() documentation
Attach a handler to an event for the elements. The handler is executed
at most once per element per event type.
Try something like this.
$(document).on('click', '#makePayment', function() {
$("body").addClass("modalPrint");
var lb = new LightBox("paymentDetailsLB", "675", "500");
lb.htmlObjRef.style.height = "auto";
lb.show();
return false;
}).on('click', '#paymentDetailsCloseLB, .hideBox', function() {
$("body").removeClass("modalPrint");
lb.hide()
}).on('click', '#paymentDetailsConfrimLB', function() {
alert('form submission happened.');
event.preventDefault();
return false;
});

The problem is:
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
it adds to the click queue, so to speak. So if you add multiple click events to something, all of them get added and all of them run by default. You don't notice it because all your other functions don't matter about being run multiple times.
A way to solve this is to put a check within the function.
$("#paymentDetailsCloseLB, .hideBox").click(function() {
$("body").removeClass("modalPrint");
lb.hide();
});//paymentDetailsCloseLB
pDCLB=$("#paymentDetailsConfrimLB");
if(!pDCLB.attr('alertc')); //check if the attribute exists, if not, we've never been here before.
pDCLB.attr('alertc',1); //adds the attribute so we can check it later.
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
}

Related

preventDefault works only once?

this trigger works correctly ONE time. If it fires again, it just refreshes my page, so I’m guessing that the preventDefault isn’t working. Am I missing something?
function watchForm() {
$(‘form’).submit(event => { //listening for event on the form pop-up menu
event.preventDefault(); //suppresses browser from going to a linked page.
$(’#js-error-message’).empty();
let searchState = $(’#js-stateMenuForm :selected’).val();
getParks(searchState); //calls getParks function.
});
}
Rewrite your function to this below and see if it works:
function watchForm(){
// for every form on the page
$('form').on('submit', function(e){
// empty the error element
$('#js-error-message').empty();
var searchState = $('#js-stateMenuForm :selected').val();
// call the function that uses the value you are looking forward to.
getParks(searchState);
// where e is the event
e.preventDefault();
return false; // force return of the form's submission
});
}
Also, you can check this post: Jquery .on() submit event

Why does my button click twice in jquery if I put it in submitHandler?

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()

JS, how to stop process execution if it's beeing executed ...?

How can I stop sending data to the server if the button allready has been clicked ? I don't want a disable="disabled" response (buttons are custom made).
I tried setting a global var button_clicked = FALSE; set it true when button has been clicked, after that set it again to false when the response has been received . But that doesnt work neither because my mouse is messed up and spam clicks really fast (although i click only once -> this actualy helped me to see that the method mentioned isn't so acurate).
Are there better methods to stop a process or disable a DOM element onClick? Maybe disable the event? js or jquery answer preferable . Or maybe this really can't be done on really fast requests . I know it depends on alot of things (like user's cpu). Any comment or answer is welcome. Maybe for every click on the page set the user to wait for some miliseconds ?
Try this little constructor:
function MyForm()
{
this.check = false;
this.form = function(){
var f = this;
$('#form').submit(function(e){
e.preventDefault
if( f.check === false )
{
f.check = true;
$.ajax({
...blah blah
success: function( data )
{
//if you want to let them send again, uncomment this next line
//f.check = false;
}
})
}
});
this.form();
}
$(document).ready(function(){
var my = new MyForm();
});
If you register an event listener, the Event object you get will have a preventDefault() method. This avoids following a clicked link or sending a submitted form.
If it is a custom action triggered by an event handler, the only possibility is to check a condition in the handler function whether the action really should be taken. Yet, a disabled button is not that bad because you will need to inform the user that nothing will happen.
Remove the click handler when the button is clicked. Add it again when you are ready for the next click.
button.onclick = null;

How to reenable event.preventDefault?

I have a web page which I have prevented the default action on all submit buttons, however I would like to re-enable default submit action on a button how can I do this?
I am currently preventing the default action using the following:
$("form").bind("submit", function(e){
e.preventDefault();
});
I have successfully done this using the following:
$(document).ready(function(){
$("form:not('#press')").bind("submit", function(e){
e.preventDefault();
});
But can I do this dynamically when the button is clicked?
You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding.
There is no magical event.cancelled=false;
As requested
$('form').submit( function(ev){
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
function(e){ e.preventDefault();
and its opposite
function(e){ return true; }
cheers!
$('form').submit( function(e){
e.preventDefault();
//later you decide you want to submit
$(this).trigger('submit'); or $(this).trigger('anyEvent');
With async actions (timers, ajax) you can override the property isDefaultPrevented like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.
// This variable is used in order to determine if we already did our js fun
var window.alreadyClicked = "NO"
$("form:not('#press')").bind("submit", function(e){
// Check if we already run js part
if(window.alreadyClicked == "NO"){
// Prevent page refresh
e.preventDefault();
// Change variable value so next time we submit the form the js wont run
window.alreadyClicked = "YES"
// Here is your actual js you need to run before doing the php part
xxxxxxxxxx
// Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
$("form:not('#press')").submit()
}
});
You can re-activate the actions by adding
this.delegateEvents(); // Re-activates the events for all the buttons
If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

jQuery/Javascript confirm coming up twice

For some weird reason i'm getting my confirm box coming up twice. here is my code:
$(".DeleteComment").live("click", function(){
var CommentID = $(this).attr("rel");
var confirm
if (!confirm('Are you sure you want to permanently delete this comment?')){
return false;
}else{
$(this).html("loading").css("color", "#999");
//AJAX HERE
return false;
}
});
Do you load any content dynamically (via ajax)? It could be the case that the click event is bound to the same element twice resulting in the double confirmation.
It happens when we bind event on the elements which are loaded dynamically via AJAX
So for example we are loading some dynamic html content (e.g. dynamic content in modal) on click of the edit form button,
And in that content if we have binded click event on some button e.g. delete button, then every time we click on edit form button, it binds the click event to delete button every time,
And if you have set confirm box on click event of delete button then, it will ask you as many time as it was binded for that click event means here if we have clicked edit form button 5 times then it will asks for your confirmation 5 times.
So for solving that issue you can unbind the event every time before binding event to dynamically loaded element as following :
$(document).off('click', '.DeleteComment').on('click', '.DeleteComment', function () {
if (confirm('Are you sure you want to permanently delete this comment?')){
//Delete process
return true;
}
return false;
}
Or Another way to solve this problem is to add your script in main page, means static page not in dynamically loaded one.
try this:
$_blockDelete = false;
$(".DeleteComment").live("click", function(event){
event.preventDefault();
//event.stopPropagation(); // it is not necessary
if (!$_blockDelete)
{
$_blockDelete =true;
var rconfirm = confirm('Are you sure you want to permanently delete this comment?');
if (rconfirm)
{
$(this).html("loading").css("color", "#999");
var CommentID = $(this).attr("rel");
//AJAX HERE
//return the value "false" the variable "$_blockDelete" once again ajax response
}
}
});
Did you try removing that not-used var confirm?

Categories

Resources