I have two forms on our site #footer_leads and #footer_leads2 and i have a live submit event but need to verify a few things before the form gets summitted so i have this code
$('#footer_leads2, #footer_leads').live('submit', function(e){
e.preventDefault();
console.log('again');
var form = $(this); //save reference to form
if(somevalidation){
form.die();
form.submit(); //submit form
}
I assumed the jQuery die event would do the trick like in the above example but the page just into an infinite loop and crashes my browser....any ideas on how to do this
From the jQuery die() page:
Note: In order for .die() to function correctly, the selector used
with it must match exactly the selector initially used with .live().
Try $('#footer_leads2, #footer_leads').die() instead.
You shouldn't need to remove the handler and resubmit. Just wait on the preventDefault() until you know whether or not the form passed validation:
$('#footer_leads2, #footer_leads').live('submit', function(e) {
if (!somevalidation)
e.preventDefault();
// Else, the form will continue submitting unimpeded.
});
Are you want to disable the form after the submit?
if yes, try this:
$('input[type=submit]', this).attr('disabled', 'disabled');
I hope its help,
Don't unbind/die.
Just submit the form with the native method.
$('#footer_leads2, #footer_leads').live('submit', function() {
if (true /* validation succeeded */ ) {
this.submit(); //submit form, but don't use jQuery's method
} else {
return false;
}
});
UPDATE:
Since it sounds like you're making an AJAX call for the validation, you could just do the this.submit() in the success: callback.
$('#footer_leads2, #footer_leads').live('submit', function() {
$.ajax({
url: 'some/path',
context: this, // set the context of the callbacks to the element
...
success: function( d ) {
if( d.is_valid ) {
this.submit();
} else {
// give some feedback to the user for validation failure
}
}
});
return false; // block the submit by default
});
From the docs ( http://api.jquery.com/die/ ) :
Note: In order for .die() to function correctly, the selector used
with it must match exactly the selector initially used with .live().
You need to use .unbind('submit')
Related
I'm trying to submit a form to Campaign Monitor. They offer this code example to POST via Ajax.
This is my code for my multi-step modal.
var next_step = false;
var final_step = false;
$('.next').on('click', function(e){
e.preventDefault();
if (next_step) {
$('#step-1').slideUp(function(){
$('#step-2').slideDown();
$('.next').html('Submit');// Change button text to submit
final_step = true;
});
}
next_step = true;
if (final_step) {
$('#myform').submit(function (e){
alert('submit started'); //This never fires unless I remove the preventDefault();
e.preventDefault();//But if I remove this, the page will refresh
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert('error');
} else {
alert('success');
}
})
});
}
});
On the last step of the form, I check whether final_step is true, if so, go ahead and submit the form via ajax.
The problem is that it just doesn't do anything? But if I remove the e.preventDefault(); from the $('#myform') it will post the form as normal and re-direct you to the form URL.
How can I fix this?
What you are doing currently is wiring up an onsubmit handler. Not invoking submit.
$('#myform').submit(function (e){ });
...is the same thing as...
<form action="#" method="post" onsubmit="return someFunction()">
... which is the same as ...
$('#myForm').on('submit', function(e){});
You are never submitting the form.
What you are looking for is to use Ajax to post the data to the server and not submit the form.
You can do that like this:
$.ajax({
type: "POST",
url: "SomeUrl.aspx",
data: dataString,
success: function() {
//display message back to user here
}
});
dataString would be replaced with the values you posting.
$('#myform').submit(function (e){
just registers an event handler and attaches it to the "submit" event of "myform", it doesn't actually cause a submit. It means you're saying you'd like this function to be run every time the form is submitted. This handler function should be outside your $('.next').on('click', function(e){ block. Just below it will do.
If, within the $('.next').on('click', function(e){ block you wish to cause the form to be submitted, write:
$('#myform').submit();
This will actually trigger the form submission.
See https://api.jquery.com/submit/ for more info on what the different method signatures of "submit" actually do.
This line: $('#myform').submit(function (e) { registers the function you pass as an argument as a handler to the submit event of the form, and does not invoke a submit action. I'm not sure whether or not this is the problem, though I would recommend preventDefault() outside of the wizard flow
(e.g.
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
}
});
)
Then inside the if(final_step) just do the post without worrying about the form.
Also, you'd do good in not setting a submit button inside the form if you do not wish to use it's functionality. Just create an element with a click event that sends the data rather than registering to the submit event of the form.
I'm not sure but I always do $('#form').submit() after click in element and catch this event (e.g. by $('#form').on('submit', function () { .. });) in other place.
Code http://jsfiddle.net/Z9qP5/1/
I want to fadeOut my form after the user submitted their email. There is the next problem. I just can't catch the submit event, so what I want, if the success message appears, then the form should be hidden. I use :visible like this:
$('#mc-embedded-subscribe-form').submit(function (e) {
if($('#mce-success-response').is(':visible')){
$("#mc_embed_signup").hide();
}
});
#mce-success-response is the success dialog.
I also tried:
if( $("#mce-success-response").css('display') == 'block') {
}
but it doesn't work. What's wrong?
yes, I think the submit event is just a one way, you just submit, and you don't want to get response when you do like that way. maybe you can use ajax that can handle the result. actually, you just submit your form, then fade out your form I think.
This is more of a workaround, and not an effective solution.
But it works!
function checkSuccess() {
if ($('#mce-success-response').is(':visible')) {
$("#mc_embed_signup").hide();
}
}
window.setInterval(checkSuccess, 100);
You could also use the code below to add a delay to the hideing:
function checkSuccess() {
function successAction(){
$("#mc_embed_signup").hide();
}
if ($('#mce-success-response').is(':visible')) {
setTimeout(successAction, 2500);
}
}
window.setInterval(checkSuccess, 100);
One possible solution is to use a custom event in this case(because as I explained in the comment the success-respone element is displayed in an ajax success handler).
So in your mce_success_cb method
if (resp.result == "success") {
$('#mce-' + resp.result + '-response').show();
$('#mce-' + resp.result + '-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function () {
this.reset();
});
$("#mc-embedded-subscribe-form").trigger('submitsuccess');
// If the form has errors, display them, inline if possible, or appended to #mce-error-response
} else {
//rest of your code
}
then
$(document).ready(function () {
$('#mc-embedded-subscribe-form').on('submitsuccess', function (e) {
$("#mc_embed_signup").hide();
});
});
Are you getting the success response from AJAX after the submit? As per your code snippet, I am assuming that to be the case and that the success boz appears once your Ajax request is completed. Since its going to be for a short while, you can try the following piece of code.
function waitForIt(){
if(!$('#mce-success-response').is(':visible')){
setTimeout(waitForIt(),500);
} else{
$("#mc_embed_signup").hide();
}
$('#mc-embedded-subscribe-form').submit(function (e) {
setTimeout(waitForIt(),500);
}
});
Alternatively, if its not the AJAX response that pops up the success message, you can try putting an interface between your form submit and the user action. Change your input type from submit to button or use a plain image as a button, i.e <img>. Use a click() instead of submit(), check if the container is visible, if yes, then hide the required container and trigger submit.
Hope it helps!
I have an Input element that submits a form:
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
I need the button to call a javascript function, and then post the form normally.
How would that be done in jQuery?
$('#downloadButton').on('click', function (e) {
e.preventDefault();
//call your function here
$(this).parents('form').submit();
});
the preventDefault() call is important because it stops the submission of the form so you can call your function before the form submit is called at the end.
You can do:
<form onsubmit="return doSomething();">
</form>
function doSomething() {
// do something
return true;
}
If in the doSomething function you don't like what you're seeing, then return false instead of true.
EDIT
The jQuery equivalent (to satisfy both commenters): remove the onsubmit from the HTML and replace with:
jQuery(document).ready(function () {
jQuery("form#myFormId").submit(doSomething);
});
Take a look at this jsfiddle
It changes the case of textbox content to to upper case before submitting the form
$('#formID').on('submit', function () {
//var form = $(this),
//input = form.find('input[type="text"]');
//input.val(input.val().toUpperCase());
//alert(input.val());
// call your function here!
});
this is what you request:
1.- click a button (adding event handler)
2.- call a function
3.- submit form
myfunction(){
//do wathever you want
$('#formid').submit();
}
$(document).on("click", "#downloadButton", myfunction);
you can do also:
$(document).on("click", "#downloadButton", function(event){
$('#formid').submit();
});
without having an extra function
but the solution of #Paritosh is the more accurate.
jsFiddle here
Change input type to type="button" and use:
$('#downloadButton').click(function() {
//Do any javascript stuff here
//And here, etc. Then, when ready...
$('#yourFormID').submit();
});
I recommend assigning an ID attribute to your form as it is good practice.
<form id="yourFormID" action="" method="POST">
Perhaps you have only one form on this page, in that case $('form').submit() is fine. But in future (or perhaps even on this page, you haven't said) you may have multiple forms on a page and therefore the ID is necessary to specify the exact form to be submitted.
Note that if you do NOT change the submit button element's <input type="submit" to <input type="button", then you must use e.preventDefault() to prevent the button's default action. Why bother with that? Just change type="button" and use less code and less future confusion.
add a submit event on form.
$('form').submit(function(event){
event.preventDefault();
var formObj = $(this);
var formData = formObj.serialize();
$.ajax({
type: 'post',
data: formData
}).done(function(response){
console.info(response);
// update UI here accordingly.
});
});
I am using jQuery with the validate plugin at http://docs.jquery.com/Plugins/Validation/validate
I want to prevent the form from submitting after its validation and submission processes done via ajax.
I have the following code:
$("#myform").validate({
rules: {...},
submitHandler: function(form) {
alert("Do some stuff...");
//submit via ajax
return false; //This doesn't prevent the form from submitting.
}
});
However, the problem with this is that the submitHandler submits the form even though I have a return false; statement at the last line of the handling function. I want prevent the default behaviour and to stop the form from submitting because I have already submitted via ajax.
How should I stop the code from submitting after going through the ajax codes in the submitHandler function?
I do it like this and it works exactly how you want it to work:
$("#myform").submit(function(e) {
e.preventDefault();
}).validate({
rules: {...},
submitHandler: function(form) {
alert("Do some stuff...");
//submit via ajax
return false; //This doesn't prevent the form from submitting.
}
});
$("#myform").validate({
rules: {...},
submitHandler: function(form, event) {
event.preventDefault();
alert("Do some stuff...");
//submit via ajax
}
});
Hope this help.
working fiddle
according to jquery plugin validation document.
submitHandler (default: native form submit)
the submission method via submitHandler below is quoted from documentation it should work , but it actually does not work they said that
Callback for handling the actual submit when the form is valid. Gets the form and the submit event as the only arguments. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
Example: Submits the form via Ajax, using jQuery Form plugin, when valid.
$("#myform").validate({
submitHandler: function(form,event) {
event.preventDefault();
$(form).ajaxSubmit();
}
});
i am writing code here what worked for me.
simply call your validayion plugin , and donot include submitHandler in your validation function arguments.
instead of submitting and preventing with submitHandler use jQuery method of form submission. like below
$("form").validate({});
$(document).on("submit", "form", function (event) {
event.preventDefault();
alert("submit");
});
Maybe you can validate externally without using a submit button:
if($("#myform").valid()){
alert("Do some stuff...");
}
You can call event.preventDefault() on submit event:
$("#myform").on("submit", function(event) {
event.preventDefault();
});
You can code this in a very simple way via "jQuery Walidate".
http://jquery.dop-trois.org/walidate/
There you can code a function, that will be executed on submit.
Look for Callback in the Documentation.
unfortunately it seems that the call: submitHandler: function(form){ does not take an event argument so it seems that the only solution is a return false statement like this:
...
submitHandler: function(form) {
//your code
return false;
},
...
I fixed this way. A patch for a jQuery Validation Plugin bug that it's not fixed even on v1.19.0
$('#save_edit_user').on('click', function () {
var isValid = $("#edit_user").validate().form() && $("#edit_user").validate().element("#edit_user_email");
//check current ajax call by $.active
//the form is not submitted before 0 ajax is running
if (isValid && $.active == 0){
// my save logic
}
});
i have a form that when submitted, if any field is empty id like to prevent the submission and add a class to the field.
For some reason I cant seem to get it too work, Ive added a fiddle, can anybody point out where im goign wrong?
http://jsfiddle.net/yycqW/
There are a couple of problems with your fiddle. Firstly, you haven't closed the ready event handler. Secondly, are passing $this into jQuery which is undefined. You need to pass this instead.
Finally, the form is always going to be submitted because you have to actually stop the submission. You can call the preventDefault method of the event object to do so. Here's a new version of your code:
$(document).ready(function(){
$("#form").submit(function(e) {
$('input').each(function() {
if ($(this).val() == '') { //Pass this into jQuery, not $this
$(this).addClass('highlight');
e.preventDefault(); //Stop the form from submitting
}
});
});
});
Also note that it's unnecessary to use $(this).val() inside the each loop. this will be a reference to a DOM element, and that element will have a value property, so it's more efficient to simply use this.value.
You're not stopping the form from actually being submitted and thus it still gets posted (and thus immediately dropping your highlights). Try adding the preventDefault method to your form and manually submit after checking for errors.
Apart from not calling preventDefault, you are using $this instead of this in one place and the brackets don't match. Working version:
http://jsfiddle.net/yycqW/7/
$(document).ready(function() {
$("#form").submit(function(e, a) {
$('input, textarea', this).each(function() {
if (!$(this).val()) {
$(this).addClass('highlight');
e.preventDefault();
} else($(this).hasClass('highlight')) ? $(this).removeClass('highlight') : false; // remove class on valid
});
});
});
Rather than preventDefault(), returning false in the function that calls the form when submitted also prevents submitting. In the previous answer, let's think that there are more than one empty fields, preventDefault() will be unnecessarily fired more than once.
I would use something like this as a cleaner solution:
$(document).ready(function(){
$("#form").submit(function(e) {
var submit=true; //A flag that we'll return
$('input').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
submit=false //Setting the flag to false will prevent form to be submitted
}
});
return submit;
});
});