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;
})
Related
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>
I have a number of fields that are either filled (inputs) or selected (dropdowns) that working together to create a new page.
I'm attempting to validate the entries and prevent the page creation if anything is wrong with the inputs. No form is being used.
The problem is the $("#netsubmit").submit(function( event )) never gets run when the submit is clicked. No errors are thrown, no indication why its not processing.
My html for the input is:
<input id="netsubmit" type="submit" value="Submit" onClick="newNet()"
title="Submit The New Net">
My JQuery javascript is:
$(document).ready(function () {
$("#netsubmit").submit(function( event ) {
alert("in it");
var callentered = $("#callsign").val();
if (callentered == "") {
event.preventDefault();
alert("Please enter a call sign first.");
$("#callsign").focus();
}
});
});
It is likely not working because as you said you aren't using a form element. From the jquery docs:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to form elements
You could use the function specified by your onclick event onClick="newNet()" to validate the data.
.submit() can only be used with <form> elements, as stated in the documentation:
It can only be attached to <form>elements.
If you do not want to use the form tag, you can switch to using .click() instead, like so:
$("#netsubmit").click(function(event) {
alert("in it");
});
If you read the documentation for submit on MDN it explicitly says
The submit event is fired when a form is submitted.
Note that submit is fired only on the form element, not the button or
submit input. (Forms are submitted, not buttons.)
if you do
<form id="myform">
<input id="netsubmit" type="submit" value="Submit" onClick="newNet()" title="Submit The New Net">
</form>
and then change the code
$(document).ready(function () {
$("#myform").submit(function( event ) {
alert("in it");
var callentered = $("#callsign").val();
if (callentered == "") {
event.preventDefault();
alert("Please enter a call sign first.");
$("#callsign").focus();
}
});
});
it works fine
I would like run function on my form submit (validate with Foundation framework) :
$($newsletter).on('formvalid.zf.abide', function(ev) {
ev.preventDefault();
alert('validate!');
openRevealNewsletter(this.getAttribute('action'));
});
I've my alert when my form is valid, but my preventDefault() don't work. My form is submitted :(
first of all easy way to make this work done is use
<button type="button">submit</button>
instead of
<button type="submit">submit</button>
to submit the form programmatically in java script use
document.getElementById("FormID").submit();
this will submit your form when you call this script also prevent default will not required once you replace submit with button in submit button
Intercept submit with submit event.
$($newsletter).on("submit",function(e) {
e.preventDefault();
console.log("submit intercepted");
return false;
});
$($newsletter).on("forminvalid.zf.abide", function(e,target) {
console.log("form is invalid");
//show error messages
});
$($newsletter).on("formvalid.zf.abide", function(e,target) {
console.log("form is valid");
//process form
openRevealNewsletter(this.getAttribute('action'));
});
Please try this:
$($newsletter).on('formvalid.zf.abide', function(ev) {
alert('validate!');
openRevealNewsletter(this.getAttribute('action'));
return false;
});
This will stop the form post on a false returned value.
When you are using return false,automatically it is doing 3 separate things when you call it:
1.event.preventDefault();
2.event.stopPropagation();
3.Stops callback execution and it returns immediately when callback are called.
I have this jQuery function injected on every page in order to disable submit buttons after they are clicked.
$('form').submit(function () {
var btn = $('input[type=submit]', this);
disableButtonOrLink.disableSubmit(btn);
btn = $('button[type=submit]', this);
disableButtonOrLink.disableSubmit(btn);
});
The problem is that I also have some backend validation that is sometimes attached to the form in the the shape of something like this
<form action="someAction" method="post" name="someForm" class="form"
onsubmit="var invalid=false;
invalid=someAction();
if(invalid){return false;}"
id="someForm">
The issue I am having that is occurs is that the ('form').submit action is always being called after the return false. The form isn't actually being submitted due to the return false; however this jQuery function is still being called after. Is there anyway to prevent this .submit from being called?
Just to clarify exactly what is happening:
The onSubmit on the form is being called;
The return false section is being hit and properly canceling the submit;
The ('form').submit is still being called after the onSubmit completes as if the form's submit wasn't canceled and is disabling buttons.
I would like to prevent the last step from occurring.
You can use JQuery to find those buttons inside form and use a method from preventing stuff that they normally do.
Example:
$("form button").on('click', function(e){
e.preventDefault();
});
I would probably try something like this
$('#someForm').on('submit', function(e) {
if ($(this).data('some-action')) {
e.preventDefault();
return false;
}
//... then disable buttons, etc
});
In this case you need to add the attribute data-some-action to the form, evaluated with whatever backend validation you are doing.
UPDATE
$('#someForm').on('submit', function(e) {
if ($(this).data('some-action') == 'error-message') {
e.preventDefault();
alert('error!');
return false;
}
if ($(this).data('some-action') == 'reload') {
e.preventDefault();
document.location.reload(true);
}
//... then disable buttons, etc
});
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();
});