I try to prevent a form submitting, with the following script, but it always does. I have even tried preventDefault() on document load, but it does not work.
$("form").submit(function() {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
return true;
}
$("span").text("Passwords do not match!").show().fadeOut(1000);
return false;
});
$("form").submit(function(e) {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
}
else{
$("span").text("Passwords do not match!").show().fadeOut(1000);
e.preventDefault();
}
});
You need to use preventDefault() to cancel the action. Note the parameter e that I added to the anonymous function call.
My suggestion, or the way I normally go about this is like this:
$("form").submit(function(e) {
e.preventDefault(); // form never fires unless I want it to
if( condition == true ) {
$(this).submit();
} else {
//Don't submit
}
}
Here is a great explanation of why preventDefault() > return false
In order for this to close I think I have found something, but it's absurd at best. My functions work when they are in a $(document).ready. Why? I would be glad to listen to your advice.
$(document).ready(function(){
$("form").submit(function() {
if ($("input").eq(3).val() == $("input").eq(4).val()) {
$("span").text("Validated...").show();
return true;
}
$("span").text("Passwords do not match!").show().fadeOut(1000);
return false;
});
});
Related
My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();
I want to check if there's at least one checkbox that checked in a form after the submit button is clicked, if no, the the user should get message and the form SHOULDN'T be submit, so I wrote this code:
jQuery(document).ready(function ($) {
$('#price_quote_create_invoice').click(function () {
$('.price-quotes-table input[type="checkbox"]').each(function () {
if ( $(this).is(':checked') ){
$('#post').submit();
return false;
} else {
alert("You didn't chose any checkbox!");
return false;
}
}) ;
});
});
However, after I press ok on the alert box, the form does submit.
Any idea why this is happening?
Your code is almost right.
You return false on a click event but what you really want to do is to stop the submit event.
Change like this.
$('#yourFormId').submit(function(){
if (!$(this).find('input[type="checkbox"]:checked').length) {
alert("You didn't chose any checkbox!");
return false;
}
});
alert('You didn't chose any checkbox!');
You have an additional comma in your alert..
You can use event.preventDefault() to do this. event is the first argument of your click function. Reference
Trying to cancel the sending of an empty form. Confused as there seems to be no reason why this doesnt work. Using firefox as my browser.
Could anybody explain why this code does not cancel the form being sent yet it fires the alert dialog.
addEvent(searchForm, "onsubmit", function(){
if(inputBox.value.trim() === ""){
alert("empty"); //this line gets called
return false; //this doesn't
}
});
Many Thanks
this is the addEvent function
function addEvent(element, listener, func){
if(element.addEventListener){
listener = listener.substr(2, listener.length);
element.addEventListener(listener, func);
} else {
element.attachListener(listener, func);
}
}
your handler should be
function(e){
if(inputBox.value.trim() == ""){
alert('empty');
e.preventDefault();
}
}
Normally regardless of the framework used handlers support passing the event itself as an argument.
addEvent is not a native javascript function.
use this instead..
searchForm.onsubmit = function(e){
if(inputBox.value.trim() === ""){
alert("empty");
e.preventDefault();
return false;
}
}
I have this code:
kreiraj_korisnika.on('submit', function(){
if(error_count != false) {
kreiraj_korisnika.submit();
} else {
return false;
}
});
How can I continue with form submitting when error_count is true (without AJAX submit)?
You have to use preventDefault() method of event variable to avoid the submit. Try sopmething like:
kreiraj_korisnika.on('submit', function(e) {
if (error_count)
{
// avoid the submit...
e.preventDefault();
// show your erros messages
}
});
If error_countvariable is true, the submit will happen.
Is kreiraj_korisnika actually an jQuery object ?
If you just assigned it to a result of getElementById() it won't work.
In that case:
$(kreiraj_korisnika).on('submit', function(e){
var errorCount = 0;
if(errorCount == 0)
{
this.submit();
}
else
{
alert('Invalid form input !');
e.preventDefault();
}
});
Léon
I have a form, and when I submit him I execute multiple script. Here is my code:
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
//How to continue submitting?
}
Is it possible to continue submitting the form (which is stopped with e.preventDefault();) after //many scripts?
Thank you
When you call $("#RequestCreateForm").submit(), the script will just run through the event handler again, and cause an infinite loop (as Koen pointed out in a comment on the accepted answer). So, you need to remove the event handler before submitting:
$("#RequestCreateForm").on('submit', function (e) {
e.preventDefault();
// do some stuff, and if it's okay:
$(this).off('submit').submit();
});
The last line needs to be in a conditional statement, otherwise it'll just always happen, and negate your e.preventDefault(); at the top.
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() === false) {
e.preventDefault();
//form was NOT ok - optionally add some error script in here
return false; //for old browsers
} else{
//form was OK - you can add some pre-send script in here
}
//$(this).submit();
//you don't have to submit manually if you didn't prevent the default event before
}
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false)
{
e.preventDefault();
return false;
}
//other scripts
}
All solutions here are too complicated or lead to javascript error, simpliest and clearest solution I guess:
jQuery("#formid").submit(function(e) {
if( ! (/*check form*/) ){ //notice the "!"
e.preventDefault();
//a bit of your code
} //else do nothing, form will submit
});
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
// Bypass the jquery form object submit and use the more basic vanilla
// javascript form object submit
$("#RequestCreateForm")[0].submit();
}
To avoid submit loops, an additional variable should be used.
var codeExecuted = false;
$('#RequestCreateForm').submit(function(e) {
...
if(!codeExecuted){
e.preventDefault();
...
functionExecuted = true;
$(this).trigger('submit');
}
});
Here is my approach to avoid the infinite loop.
In the form, I use a "button" with an id (e.g. <input type="button" id="submit" value="submit"/>) to mimic the submit button;
In the script I have something like this:
$('#submit').click(function() {
if(//validation rules is ok)
{
$("#RequestCreateForm").submit(); //assuming the form id is #RequestCreateForm
}
else
{
return false;
}
});
return; is the same thing as e.preventDefault();
try
$("#RequestCreateForm").trigger('submit');