Prevent form from submitting multiple times - javascript

I have some code where I'm trying to prevent a form from being submitted multiple times. I found this code on another Stack thread but it doesn't work. Instead it submits the form infinite times and lags the entire server!
$(document).ready(function() {
$('form').submit(function() {
console.log("hi")
if ($(this).valid()) {
$(this).submit(function(){
return false;
});
return true; //Tried with an without
}
});
});
Here is a picture of the output in the console:
This keep submitting the form. I just took a picture at that number.
The thread that I found the code above from is the accepted answer on this question and it has many upvotes.
Note that I have multiple forms per page, and many pages with many forms! A solution to one specific form is not sufficient. I need a global solution. Also I'm using Codeigniter.

Try passing in the event and using e.preventDefault()
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
console.log("hi")
if ($(this).valid()) {
$(this).submit(function(){
return false;
});
}
});
});

Correct me if I'm wrong but, shouldn't you just return; if it's valid, else stop submission like in the jQuery documentation's example.
$(document).ready(function() {
$('form').submit(function(event) {
console.log("hi")
if ($(this).valid()) {
return;
}
event.preventDefault();
});
});

You need to cancel the initial form submission so that you only do it after you've validated it. But frankly, HTML5 won't submit if a form is not valid, so your code seems redundant.
Here is a working example that takes most of the JQuery out of the mix. It only submits the form one time.
You can also test it here: https://jsfiddle.net/5oyp6aa0/6/
$(function() {
var theForm = document.querySelector("form");
theForm.addEventListener("submit",function(evt) {
// First, cancel the form's submission:
evt.preventDefault();
evt.stopPropagation();
console.log("Navitve Submit Cancelled")
if (theForm.checkValidity()) {
// Then, only if it's valid, submit
console.log("Manual Submit Triggered");
theForm.submit();
}
});
});

After none of these answers worked I decided to give it another shot. This works for me.
$(document).ready(function() {
$("form").submit(function (e) {
var attr = $(this).attr('submitted');
if (typeof attr === typeof undefined || attr === false) {
if ($(this).valid()) {
$(this).attr('submitted', 'submitted');
$(this).submit();
} else {
e.preventDefault();
}
} else {
e.preventDefault();
}
});
});

Related

How to prevent form submission in javascript

I have written code like this to prevent form submit. But it is not working. What is the possible reason
$('#signUpForm').submit(function (event) {
debugger;
console.log('test');
event.preventDefault();
$('#signUpForm').unbind().submit();
//IsValid();
return false;
})
Try this solution:
$(document).ready(function() {
$("#signUpForm").on("submit",function(e){
e.preventDefault(e);
console.log("form submission canceled");
});
});
Supposing you have only 1 form in your html page
$(document).ready(function() {
$("form").submit(function(e){
e.preventDefault(e);
console.log("form submission canceled");
});
});
According to the jQuery documentation your syntax seems to be wrong.
Also, .unbind() is deprecated. Prefer .off()
try
$('#signUpForm').unbind('submit')

validate textbox without postback

Good morning/afternoon/evening to all of you, Sir/Ma'am, I have a question regarding my code below. What my code does is to validate the textbox without postback. What I wanted to do is to show alert "hello" if the textbox has a value of "set". I'm truly grateful if you do reply and answer my question. I'm really sorry if my code below is kind of rubbish because I'm new to javascript and jquery.
$(document).ready(function () {
var fset = document.getElementById('<%=fname.ClientID%>').value;
if(fset.value=="set"){alert("hello");}
else{}
});
You either do the validation on form submit, onblur of the field or on keyup on the field. There other places that I'm not thinking of that you could do the client side as well.
Here's a version of on key up:
$(document).ready(function() {
$("#<%=fname.ClientID%>").on("keyup", function() {
if ( $(this).val() == "set" ) {
alert("hello");
}
});
});
If you have a form you could do:
$(document).ready(function() {
$("form").on("submit", function() {
if ( $("#<%=fname.ClientID%>").val() == "set" ) {
alert("hello");
}
});
});

jQuery alert not working in IE 8

I have the following script that is not working in IE 8, it works in other browsers fine but in IE 8... all the user gets, even with the checkbox input selected is alert. Any thoughts would be greatly appreciated.
$(function() {
$("form#insider-account").bind("keypress", function(e) {
if (e.keyCode == 13) return false;
});
var isChecked = false;
$("form#insider-account").change(function() {
if ($("input#insideraccount_verified").is(":checked")) {
isChecked = true;
} else {
isChecked = false;
}
});
$("form#insider-account").submit(function(e) {
if (!isChecked) {
e.preventDefault();
alert("You must agree that the information you provided is correct.");
}
else {
}
});
});
Not sure why you set isChecked in a separate event from the submit-event. I think your problem is that in IE8, this:
$("form#insider-account").change(...
Isn't triggered when a control inside the form is changed. Why not attach the change event to the control itself:
$("input#insideraccount_verified").change(...
Or, better, just check that the checkbox is checked in the submit event instead of using a variable that you set in some other event:
$("form#insider-account").submit(function (e) {
if (!$("input#insideraccount_verified").is(":checked")) {
e.preventDefault();
alert("You must agree that the information you provided is correct.");
}
else {
}
});
Listen for change on elements inside the form instead of the form iteself, after searching google for "form change ie jquery" there were a number of results stating that this was an issue including jQuery .change() event not firing in IE
It's suggested there to use the on event instead, which will listen to the change event for input elements inside your form, like so:
$("form#insider-account input").on('change', function() {
isChecked = $("input#insideraccount_verified").is(":checked");
});

What is the opposite of evt.preventDefault();

Once I've fired an evt.preventDefault(), how can I resume default actions again?
As per commented by #Prescott, the opposite of:
evt.preventDefault();
Could be:
Essentially equating to 'do default', since we're no longer preventing it.
Otherwise I'm inclined to point you to the answers provided by another comments and answers:
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
How to reenable event.preventDefault?
Note that the second one has been accepted with an example solution, given by redsquare (posted here for a direct solution in case this isn't closed as duplicate):
$('form').submit( function(ev) {
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
function(evt) {evt.preventDefault();}
and its opposite
function(evt) {return true;}
cheers!
To process a command before continue a link from a click event in jQuery:
Eg: Click me
Prevent and follow through with jQuery:
$('a.myevent').click(function(event) {
event.preventDefault();
// Do my commands
if( myEventThingFirst() )
{
// then redirect to original location
window.location = this.href;
}
else
{
alert("Couldn't do my thing first");
}
});
Or simply run window.location = this.href; after the preventDefault();
OK ! it works for the click event :
$("#submit").click(function(event){
event.preventDefault();
// -> block the click of the sumbit ... do what you want
// the html click submit work now !
$("#submit").unbind('click').click();
});
event.preventDefault(); //or event.returnValue = false;
and its opposite(standard) :
event.returnValue = true;
source:
https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue
I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
I would suggest the following pattern:
document.getElementById("foo").onsubmit = function(e) {
if (document.getElementById("test").value == "test") {
return true;
} else {
e.preventDefault();
}
}
<form id="foo">
<input id="test"/>
<input type="submit"/>
</form>
...unless I'm missing something.
http://jsfiddle.net/DdvcX/
This is what I used to set it:
$("body").on('touchmove', function(e){
e.preventDefault();
});
And to undo it:
$("body").unbind("touchmove");
There is no opposite method of event.preventDefault() to understand why you first have to look into what event.preventDefault() does when you call it.
Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).
As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.
See below for an explanation:
;(function($, window, document, undefined)) {
$(function() {
// By default deny the submit
var allowSubmit = false;
$("#someform").on("submit", function(event) {
if (!allowSubmit) {
event.preventDefault();
// Your code logic in here (maybe form validation or something)
// Then you set allowSubmit to true so this code is bypassed
allowSubmit = true;
}
});
});
})(jQuery, window, document);
In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.
This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.
Here's something useful...
First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.
Google
<script type="text/javascript">
$(document).ready(function() {
$("#link").click(function(e) {
// Prevent default action
e.preventDefault();
// Here you'll put your code, what you want to execute before default action
alert(123);
// Prevent infinite loop
$(this).unbind('click');
// Execute default action
e.currentTarget.click();
});
});
</script>
None of the solutions helped me here and I did this to solve my situation.
<a onclick="return clickEvent(event);" href="/contact-us">
And the function clickEvent(),
function clickEvent(event) {
event.preventDefault();
// do your thing here
// remove the onclick event trigger and continue with the event
event.target.parentElement.onclick = null;
event.target.parentElement.click();
}
I supose the "opposite" would be to simulate an event. You could use .createEvent()
Following Mozilla's example:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var cancelled = !cb.dispatchEvent(evt);
if(cancelled) {
// A handler called preventDefault
alert("cancelled");
} else {
// None of the handlers called preventDefault
alert("not cancelled");
}
}
Ref: document.createEvent
jQuery has .trigger() so you can trigger events on elements -- sometimes useful.
$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
This is not a direct answer for the question but it may help someone. My point is you only call preventDefault() based on some conditions as there is no point of having an event if you call preventDefault() for all the cases. So having if conditions and calling preventDefault() only when the condition/s satisfied will work the function in usual way for the other cases.
$('.btnEdit').click(function(e) {
var status = $(this).closest('tr').find('td').eq(3).html().trim();
var tripId = $(this).attr('tripId');
if (status == 'Completed') {
e.preventDefault();
alert("You can't edit completed reservations");
} else if (tripId != '') {
e.preventDefault();
alert("You can't edit a reservation which is already attached to a trip");
}
//else it will continue as usual
});
jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.
jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.
$( selector ).on("submit.my-namespace", function( event ) {
//prevent the event
event.preventDefault();
//cache the selector
var $this = $(this);
if ( my_condition_is_true ) {
//when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
$this.off("submit.my-namespace").trigger("submit");
}
});
now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..
you can use this after "preventDefault" method
//Here evt.target return default event (eg : defult url etc)
var defaultEvent=evt.target;
//Here we save default event ..
if("true")
{
//activate default event..
location.href(defaultEvent);
}
You can always use this attached to some click event in your script:
location.href = this.href;
example of usage is:
jQuery('a').click(function(e) {
location.href = this.href;
});
In a Synchronous flow, you call e.preventDefault() only when you need to:
a_link.addEventListener('click', (e) => {
if( conditionFailed ) {
e.preventDefault();
// return;
}
// continue with default behaviour i.e redirect to href
});
In an Asynchronous flow, you have many ways but one that is quite common is using window.location:
a_link.addEventListener('click', (e) => {
e.preventDefault(); // prevent default any way
const self = this;
call_returning_promise()
.then(res => {
if(res) {
window.location.replace( self.href );
}
});
});
You can for sure make the above flow synchronous by using async-await
this code worked for me to re-instantiate the event after i had used :
event.preventDefault(); to disable the event.
event.preventDefault = false;
I have used the following code. It works fine for me.
$('a').bind('click', function(e) {
e.stopPropagation();
});

How to validate form using JQuery when only one particular button is pressed?

I have a form with two submit buttons on it. Buttons must be of submit type and I can't change it.
How can I make jquery not to validate but submit the form when first button is pressed and validate and submit when second button is pressed?
thank you
Ok, I found a solution which is ridiculously easy as usual, the only thing I need to do is to set class="cancel" to the first button and it'll skip validation on submit.
Found here http://forum.jquery.com/topic/stop-a-specific-button-calling-validation
event.originalEvent.explicitOriginalTarget is a Gecko-specific property (see this question and answer).
The following should work:
var doValidate;
$('#validating-button').click(function () { doValidate = true; });
$('#non-validating-button').click(function () { doValidate = false; });
$('#form').validate({
rules: {
myinputname: {
required: function () { return doValidate; }
}
}
});
EDIT: check questioneer's answer :)
First btn clicked, do validation stuff and check validation (just try it/improve it)... Second Btn clicked, just do nothing (submit form)
$('#formid').submit(function(event) {
if (event.originalEvent.explicitOriginalTarget.id == "firstButtonID") {
$(this).validate();
if(!$(this).valid()){
event.preventDefault();
return false;
}
}
});

Categories

Resources