Cancel a $('form').submit() call in jQuery - javascript

I'm in trouble when I use form submit event in jQuery.
Markups
<form>
<input type="text" name="username" />
<a id="btn_submit">Submit</a>
<input type="submit" />
</form>
Event listener
function valid() { return false; }
$('form').submit(function() {
if(!valid()) {
return false;
}
});
Then, when I click that <input type="submit" /> it do trigger that event, and can cancel the submit event.
But when I trigger the form submit on the .btn_submit tag, return false cannot cancel the submit.
Failure of cancel
$('#btn_submit').click(function() {
$('form').submit();
// $('form').trigger('submit');
// document.forms[0].submit();
});
So, now the question is, if I must use an a.btn_submit to trigger the submit of form, and I want to cancel that submit in case.
How should I trigger?
How should I cancel?
Please help!
I made a fiddle http://jsfiddle.net/69wcduv5/2/.
But it seemed cannot submit in jsfiddle.
My final solution (a bit dirty)
I can create a submit input inside the form, then trigger a click on it. Then remove it.
If I trigger the submit in this way, I acts exactly the same as I expected:
The validation code inside the $('form').submit(function() {}); don't have to change.
If the form has something like <input type="text" required />, it can do well.
I can style well on that anchor. Not the f**king <input type="submit" />
Thank you all for your patient, best regards.
And hoping for a clean better solution.

$("a.btn_submit").click(function(){
if($('form').valid())
{
$('form').submit();
}
});

$('form').submit(function(event) {
if(!valid()) {
event.preventDefault();
}
});

Seems weird to use a link to submit a form, but your problem is you are not cancelling the click action on the anchor.
$('.btn_submit').on("click", function(evt) {
evt.preventDefault();
$('form').submit();
});

I understand now what you are trying to achieve, so please ignore what I wrote before.
formElement.submit() and its jQuery equivalent very deliberately do not trigger an onsumbit event. Othwise there is the potential for infinite recursion.
Therefore, you cannot execute $('form').submit(); and hope for an onsubmit handler to intercept.
Your best bet is probably your "dirty" idea. Namely to trigger a click on a (hidden) type="submit" button.

Call the submit in this way, the most close to my intention:
$.fn.natural_submit = function() {
if($(this).is('form')) {
var $form = $(this);
var $input_submit = $('<input type="submit" />').hide().appendTo($form);
$input_submit.trigger('click');
$input_submit.remove();
}
}
$('#btn_submit').click(function() {
$('form').natural_submit();
});

Related

Why does checkValidity or reportValidity triger automatic submit of a form in jquery?

Consider the following code:
$("button[type='submit']").click(function(e){
if($(this).closest("form").checkValidity()) {
$(this).closest("form").reportValidity();
}
e.preventDefault();
alert("Never happens!!!");
});
If the input data is valid and then I press the submit button, the php form is submitted without letting e.preventDefault(); and alert("Never happens!!!"); to get executed. I suspect this happens because checkValidity and reportValidity return true, which acts as a return true; statement.
Consider this code:
$("button[type='submit']").click(function(e){
e.preventDefault();
alert("Does happen!!!");
});
This time I see the alert, meaning preventDefault stopped the form from being submitted. What is strange to me even if checkValidity and reportValidity return true, how can they act as return statement for the jquery click function?
It should be noted that the following approach doesn't work either:
$("button[type='submit']").click(function(e){
e.preventDefault();
if($(this).closest("form").checkValidity()) {
$(this).closest("form").reportValidity();
}
alert("Never happens!!!");
});
I think preventDefault prevents checkValidity and reportValidity to work properly and forces them to return false, which somehow acts as return false; statement causing the alert to not get executed.
Another possible explanation could be that calling either checkValidity or reportValidity causes the form to get submitted. I don't know why would that be the case.
Please give an explanation with reference to official documentation.
checkValidity() and reportValidity() are not methods of a jQuery object. You need to call them on the underlying form Element object instead.
It also seems from the context that the logic in the if condition needs to be inverted so that the reportValidity() is called only when the form is invalid - along with the e.preventDefault() to stop the actual form submission.
$("button[type='submit']").click(function(e) {
let form = $(this).closest('form').get(0);
if (!form.checkValidity()) {
form.reportValidity();
e.preventDefault();
}
console.log("Will always happen");
});
<form>
<input type="text" name="foo" value="" required />
<button type="submit">Submit</button>
</form>
That being said, your JS code is completely redundant as you get this exact behaviour for free by default when you apply the required attribute to any control within the form:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="foo" value="" required />
<button type="submit">Submit</button>
</form>

How to intercept a submit button click?

I have a form and a submit button.
I want to do a quick check on some of the fields (if one isn't filled in, then to blank some of the others).
I would rather not change the HTML for the button, I would like to just to do this in jQuery and not add any "onclick" attributes to the button.
HTML:
<input class="cssButton button_in_cart" type="submit" value="Add to Bag" style="width: 80px;">
jQuery (attempted):
$("input.button_in_cart").mousedown(function () {
alert("clicked");
});
This doesn't work, it still submits the form without showing the alert. Thanks.
Do not use any form of click event for form processing as keyboard submission will bypass your code!
Use the submit event handler instead and return false (or e.preventDefault()) to stop the submit proceeding.
e.g.
$('#myform').submit(function(e){
// Do your validation here
// ...
// Then conditionally stop the submit from firing
if (someValidateFails){
e.preventDefault()
}
});
You can use the return value of the function to prevent the form submission
<form name="myForm" onsubmit="return validateMyForm();">
and function like
<script type="text/javascript">
function validateMyForm()
{
if(check if your conditions are not satisfying)
{
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
</script>
In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.
make type as 'button' first
<input class="cssButton button_in_cart" type="submit" value="Add to Bag" style="width: 80px;">
$("input.button_in_cart").mousedown(function (e) {
e.preventDefault();
alert("clicked");
// do the form submit
document.forms[0].submit();
});
There are two main ways to "stop" an event.
The first one is to return false; and the other one is to e.preventDefault();.
Teh difference in these two ways is that using e.preventDefault(); will stop the entire event from proceeding and won't propagate the DOM.
I would use the following:
$("input.button_in_cart").mousedown(function () {
alert("clicked");
return false;
})

Simplest way to disable button on submission of a form?

I've been trying to find the "right" way to prevent double submits of forms. There are lots of related posts on SO but none of them hit the spot for me. Two questions below.
Here is my form
<form method="POST">
<input type="text" name="q"/>
<button class="once-only">Send</button>
</form>
Here is my first attempt to disable double submits:
$(document).ready(function(){
$(".once-only").click(function(){
this.disabled = true;
return true;
});
});
This is the approach suggested here: Disable button after post using JS/Jquery. That post suggests the submitting element must be an input rather than a button, but testing both makes no difference. You can try it yourself using this fiddle: http://jsfiddle.net/uT3hP/
As you can see, this disables the button, but also prevents submission of the form. In cases where the submitting element is a button and an input element.
Question 1: why does this click handler stop submission of the form?
Searching around some more I find this solution (from Why doesn't my form post when I disable the submit button to prevent double clicking?)
if($.data(this, 'clicked')){
return false;
} else{
$.data(this, 'clicked', true);
return true;
}
You can play with this using this fiddle: http://jsfiddle.net/uT3hP/1/
This does work, but...
Question 2: Is this the best we can do?
I thought this would be an elementary thing. Approach 1 does not work, approach 2 does, but I don't like it and sense there must be a simpler way.
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
You can use jQuery's submit(). In this case, it should look something like this:
$('form').submit(function(){
$(this).children('input[type=submit]').prop('disabled', true);
});
Here is a working jsFiddle (made by Mike) - http://jsfiddle.net/gKFLG/1/.
If your submit-button is not a direct child of the form-element you will need to replace children with find. Additionally, your submit-button may also be a button element instead of an input element. E.g. This is the case if you are using Bootstrap horizontal forms. Below is a different version of the snippet:
$('form').submit(function(){
$(this).find('button[type=submit]').prop('disabled', true);
});
Demo jsFiddle - http://jsfiddle.net/devillers/fr7gmbcy/
Similarly Ive seen a few examples, this one allows you to alter how long the button is disabled for, through timeout. It also only triggers on a form submit rather than on the buttons click event, which originally caused me a few issues.
$('form').submit(function () {
var button = $('#button');
var oldValue = button.value;
var isDisabled = true;
button.attr('disabled', isDisabled);
setTimeout(function () {
button.value = oldValue;
button.attr('disabled', !isDisabled);
}, 3000)
});
You could try using the following code:
$(document).ready(function(){
$(".once-only").click(function(){
this.submit();
this.disabled = true;
return true;
});
});
This should help:
<form class="form-once-only" method="POST">
<input type="text" name="q"/>
<button type="submit" class="once-only">Send</button>
</form>
Javascript:
$(document).ready(function(){
$("form.form-once-only").submit(function () {
$(this).find(':button').prop('disabled', true);
});
}

OnClick bypasses form submit

I have a form which is made like this:
<form id= 'lol' name = 'whyyyyy'>
<input name='dumbo'>
<input name='idiot'>
<input type='submit' value='I have no idea why its like this' onclick='document.lol.submit()'>
</form>
Now, I want to prevent the actual sending of the form, but so far all attempts failed.
My current code looks like this:
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
})
but the inline submit command bypasses as it seems the jQuery function.
Can someone shred light into it?
EDIT:
The form CANNOT be changed, I don't have permission to change.
the on click code should trigger the submit function, it some complex validation wall of code in it. So I have to cache the submit action that it triggers, but I can't do that at moment.
the submit function should be triggered on send but it does not get triggered.
Here is an example of the code in jfiddle. As you can see it gets past by jQuery...
http://jsfiddle.net/StCPp/4/
if you don't need a submit button, why don't you use a regular button instead
<input type="button" />
<input type='button' value='i have no idea why he done it like this' onclick='document.getElementById('lol').submit()'>
Just use a normal button instead of a submit.
If you want to bypass a submit button you can make the class of the button cancel.
<input type='submit' class='cancel' value='i have no idea why he done it like this' onclick='document.lol.submit()'>
In your add-on JavaScript, remove the inline onclick event and replace it with whatever you desire. Problem solved.
You could also completely remove his button and replace it with one of your choice.
Remove the document.lol.submit function. This way, you can do whatever you want.
// Magic line
delete document.lol.submit;
// Or
$('form[name="whyyyyy"] input[type=submit]').attr('onclick', '');
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
});
Ok so if I got this right you could remove the inline event handler onclick and add your custom handler (where you do the validation and all necessary steps):
$(document).ready(function() {
var $submit_button = $('input[type=submit]');
$submit_button.removeAttr('onclick');
$submit_button.click(function() {
//TODO: implement your custom handler
//execute validation etc.
});
});
Remove the onclick
$('input[type=submit]').attr('onclick','')
Then add the click event to function ready
$('input[type=submit]').on('click',function(){
//do your event
});
You aren't necessarily required to use jquery to implement this. You could use standard javascript.
$(document).ready(function(){
document.whyyyyy.submit = function(e){
alert(1);
return false;
};
});
This example works, but you might be hitting a jquery bug.

Disable button after submit with jQuery

I know there are a lot of questions about it, but I tried several solutions, and nothing works.
In my django app I have a form:
<form method='post'>
<button type='submit'>Send</button>
</form>
I wan't to disable the button once the user has submitted the form. Using other questions, I tried several things, like:
<button type='submit' onclick="this.disabled=true">Send</button>
When I click, the button is disabled... but the form is not submitted. And for each try I had the same issue: either the button is disabled or the form is submitted. I can't find how to do both...
I'm using Chrome. Any idea on why I have this problem? Thank you for your help.
Try this:
$('form').submit(function() {
$(this).find("button[type='submit']").prop('disabled',true);
});
I like this, don't have to traverse the DOM.
Put function on a setTimeout function, this allows make submit and after disable button, even if setTimeout is 0
$(document).ready(function () {
$("#btnSubmit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$("#btnSubmit").prop('disabled', true);
}
});
You could disable it upon the parent form's submit event:
$("form").on("submit", function () {
$(this).find(":submit").prop("disabled", true);
});
Be sure to run this code only after the HTMLFormElement has been loaded, or else nothing will be bound to it. To ensure that the binding takes place, fire this off from within a document-ready block:
// When the document is ready, call setup
$(document).ready(setup);
function setup () {
$("form").on("submit", function () {
$(this).find(":submit").prop("disabled", true);
});
}
Something like this might work.
<button id="btnSubmit" type='submit'> Send </button>
<script>
$("#btnSubmit").on("click", function(e){
e.PreventDefault();
$(this).closest("form")[0].submit();
$(this).prop('disabled',true)
});
</script>
Try, like this,
<input type="submit" value="Send" onclick="javascript=this.disabled = true; form.submit();">
This ended up being the best solution for me
$("form").submit(function disableSubmit() {
$("input[type=submit]", this).prop("disabled", true);
});
my variant, disable button, no direct disabled but only vidible hidden:
<input type="submit" name="namebutton" value="Nahrát obrázek" onclick="this.style.visibility='hidden';" ondblclick="this.style.visibility='hidden';"/>
You can do something like this. It is work fine with me.
<form method='post' onSubmit='disableFunction()'>
// your code here
</form>
Then in script, add this
<script>
function disableFunction() {
$('#btn_submit').prop('disabled', true);
}
</script>
How about this?
onclick="this.style.visibility='hidden';"
I would say, instead of disabled, hide it.
If you want to go with disabled
onclick="this.style.disabled='true';"
Got an issue on Chrome, wasn't submitting the form. Tried a bunch of different code, this was what worked best for me (and looks best imo):
$('#form_id').submit(function() {
$("input[type='submit']", this)
.val("Please Wait...")
.attr('disabled', 'disabled');
return true;
});
Replace form_id with the id of your form. Classes work too of course: $('.form_class')
Source: JavaScript Coder
I like this better:
<script>
var submit = false;
$('form').submit(function () {
if (submit) { return false; }
else { submit = true;}
});
</script>
this way it also prevents the enter key to submit more than once
I'm using Chrome. Any idea on why I have this problem?
Well, first time I dealt with this, I solved it like this:
function blockButtons() {
$('button:submit').click(function(){
$('button:submit').attr("disabled", true);
});
}
This worked perfectly, but... in Mozilla Firefox. The Google Chrome did not submit it, so I changed it to this:
function blockButtons() {
$('button:submit').click(function(){
var form = $(this).parents('form:first');
$('button:submit').attr("disabled", true);
$('button:submit').css('opacity', 0.5);
form.submit();
});
}
This worked both in Mozilla Firefox, however, after that some of our users using old versions of IE experienced trouble of having two submits. That is, the one initiated by the javascript, and the one by browser ignoring the fact of onclick and just submitting anyway. This can be fixed by e.preventDefault, I guess.
If you don't want an element to be double-clicked, use .one()
<button id="submit" type="submit">Send</button>
<script>
$(function () {
$("#submit").one("click", function () {
//enter your submit code
});
});
.one()
You can do something like this. It is work fine with me.
$("button#submitted").click(function () {
$("button#submitted").prop('disabled', true);
});
Double click on your button. This code will running
You must prevent the form from being submitted more than once, disabling the button is not the right solution because the form could be submitted in other ways.
JavaScript:
$('form').submit(function(e) {
// if the form is disabled don't allow submit
if ($(this).hasClass('disabled')) {
e.preventDefault();
return;
}
$(this).addClass('disabled');
});
Once the form is correctly disabled, you can customize its appearance.
CSS:
form.disabled {
pointer-events: none;
opacity: 0.7;
}

Categories

Resources