On submit function is not called - javascript

At the end of the document I have:
<script>
$("#submitEvent").click(function() {
$("#eventForm").submit();
});
$(document).ready(function() {
$('#eventForm').submit(function() {
console.log("I am on submit");
}); });
</script>
Now submitEvent is button which is not within a form so and the reason for having on .click event.
When button is pressed the form submit is triggered correctly:
<form id="eventForm" action="${contextPath}/dashboard/event/new"
method="post">
Now I expect another event to be fired when submit is fired which actually is ignored for some reason. Instead of console.log I am not surprisingly going to use ajax, but even console.log does not print anything so the event is not triggered..
Update, did as you suggested still nothing :-) :
$(document).ready(function() {
$("#submitEvent").click(function() {
$("#eventForm").submit();
});
$('#eventForm').submit(function() {
console.log("I am on submit");
});
});

If your reason for saying the form submit handler isn't being called is that you don't see the output in the console, remember that submitting a form completely tears down and replaces the page. You probably don't have time to see the log message before the console gets cleared.
In a comment, you said:
Hm, so how can I check if ajax will be called.
You can check by setting a breakpoint on your console.log statement and seeing if the breakpoint gets hit. Or if you want to debug 1990's-style, use an alert.
But note that doing ajax from within a form submit handler, if the form's result will replace the page, is unreliable. (If the form's result won't replace the page, you're probably fine.) This is because ajax is asynchronous, meaning your submit handler could start it, but it wouldn't have time to finish before being cancelled by the teardown.

Try this...
$(document).ready(function() {
$("#submitEvent").click(function() {
$("#eventForm").submit();
});
$('#eventForm').submit(function(e) {
e.preventDefault();
console.log("I am on submit");
});
});
It will stop the form submitting so you can see, for now, if the event is actually being triggered or not.
It may simply be that the form being submitted is reloading the page before you see the console output.

You just need to move your code inside the ready function
<script>
$(document).ready(function() {
$("#submitEvent").click(function() {
// run ajjax code here
});
$('#eventForm').submit(function(e) {
e.preventDefault(); // stops the page from submiting
console.log("I am on submit");
});
});
</script>
I updated the code, you don't need to submit the form. just run ajax on click.

Related

How to trigger submitting form automatically and use preventDefault

I have two ways of using form on a page.
First one is standard way when user types something in input field and clicks the submit button.
Second one is that the form is automatically filled and submitted depending on if a query string is passed to a page. (www.website.com/contact?fillform=true)
Everything works fine except I need yet to trigger the submit button for when query string is passed but currently it just refreshes the page.
I have done part in PHP, I have checked variables and they are ok.
Here is Codepen, e.preventDefault() is commented out since it doesn't work on window load
$(window).load(function() {
// Function for submitting form
function submitForm(e) {
console.log('I am in');
e.preventDefault();
jQuery.ajax({
... // Submit form
})
}
// Normal way of submitting form, works ok
$contactForm.on('submit', function(e) {
submitForm(e);
});
// This should trigger form automatically
if(fillFormAutomatically) {
// Everything so far works ok
// I just need to trigger form without page refresh but none of these works
$submitBtn.trigger('click');
$submitBtn.triggerHandler('click');
$contactForm.submit(e);
$contactForm.submit(function(e) {
console.log(e); // nothing in console shows here
submitForm(e);
});
submitForm(); // This triggers function but I can't pass event?
}
});
I think there is a couple of problems.
.load() was depreciated in jQuery 1.8, so don't use that. See: https://api.jquery.com/load-event/
Secondly, when you call submitForm() on window.ready(), there is no event. So you're trying to call .preventDefault() on undefined. Just move it to the .submit() function.
Does that answer your question?
$(window).ready(function() {
var $form = $("#form");
var $submitBtn = $("#submitBtn");
// Send form on window load
submitForm();
// Normal way
$form.submit(function(e) {
e.preventDefault();
submitForm(e);
});
// Send form
function submitForm() {
$('#vardump').append('Sending form...');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="form">
<input type="text" value="Somedata">
<button id="submitBtn">Submit</button>
</form>
<div id="vardump"></div>

Javascript code submits form on the same page in Mozilla

I have this code that I use, to add fields in a form, when button is pressed:
$(".add-participant").on("click", function() {
event.preventDefault()
$(".participant.hidden").first().removeClass("hidden");
if(!$(".participant.hidden").length) {
$(this).hide();
}
});
I added the event.preventDefault() because the button to add (unhide) the fields, was submitting the form for some reason.
This works on Chrome/Edge/IE, but on Mozilla it does not, for some reason. Form tries to submit, instead of the fields getting unhidden. Any ideas how to solve this?
The only problem that I find in your code is that your event is undefined. Modify your code slightly to define an event as:
$(".add-participant").on("click", function(event) {
event.preventDefault()
$(".participant.hidden").first().removeClass("hidden");
if(!$(".participant.hidden").length) {
$(this).hide();
}
});
This should solve your problem.

jQuery form getting submitted multiple times

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
}

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

Aweber form not collecting leads because of simple jquery code [duplicate]

I have a form that uploads a file and targets an iframe on the page. When the user clicks submit, I want the file contents to "clear" out.
I tried this
$('#imageaddform').submit(function(){
$('#imagefile').val('');
});
But it clears the form before the submit, so nothing is ever uploaded.
Is how do I clear after submit?
If you have no other handlers bound, you could do something like this:
$('#imageaddform').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
$('#imagefile').val(''); // blank the input
});
Lonesomeday's solution worked for me but for Google Chrome I found it would still submit empty form data unless I added a timeout like this:
$('#imageaddform').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
setTimeout(function(){ // Delay for Chrome
$('#imagefile').val(''); // blank the input
}, 100);
});
You could do something like this:
$('#imageaddform').submit(function(){
setTimeout(function() {
$('#imagefile').val('');
},100);
});
How are u submitting the form? if this is normal form post then then page wont exist in that case i am wondering if u are looking to clear the form before the page refreshses so that when the user comes back he doesn't see the values populated.
If the form is submitted by ajax then you can
function(){
$('form1')[0].submit();
clearForm();
}
Did i miss the question?

Categories

Resources