I was using this first:
HTML:
<form onsubmit="return validate()">
...
<input type="submit" id="submit-button"/>
</form>
JS:
function validate() {
// many lines for a big validation with regex and so on...
$('form').submit();
}
I noticed, that this was loading very long, so I changed it to:
HTML:
<form>
...
<input type="submit" id="submit-button"/>
</form>
JS:
function validate() {
// many lines for a big validation with regex and so on...
$('form').submit();
}
$('#submit-button').on('click', function(e) {
e.preventDefault();
validate();
});
And the loading time was OK and about 100 times faster!
Can someone give me a - hopefully - short answer to this?
On the first example, you are firing a submit event inside the submit callback, then the call stack exceeds [see fiddle].
The second example relies on a click event, so things seem to work, but you should better fire your HTTP call via ajax after validation.
Your function is called validate(), but I don't see any validation, just a submit event. The thing is, the way you have it set-up is wrong. validate() should be returning true/false so the form knows if it should continue or not. So instead, your validate function should look more like this:
function validate() {
//many lines for a big validation with regex and so on...
if (val=='') { return false; }
else { return true; }
}
Now your form will only submit when the validate() function returns true, otherwise, it will not continue. This will fix your issue, so you are not looping out.
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 know this has to be something obvious, but even after following instructions elsewhere, I'm getting the same result.
The alert on the JavaScript call comes up, but after clicking okay, it continues to submit the form.
function validateBadEmail(inputText)
{
var mailformat = /.ru$/
if(inputText.value.match(mailformat))
{
alert("This is not an accepted email address");
inputText.preventDefault();
}
}
Here is how I'm calling it:
<input type="button" id="submit-btn" class="btn btn-blue btn-less-padding" name="submit-btn" value="<?= $txt_submit_btn; ?>" tabindex="0" onclick="return validateBadEmail(document.the_form.email)"/>
I have tried this by using return false instead of preventDefault but that's having the same effect.
If I change the onclick to onsubmit it doesn't even call the javascript at all.
Edit: clearly preventDefault is the wrong way, but if I try to do it this way, I'm still getting the same results
function validateBadEmail(inputText)
{
var mailformat = /.ru$/
if(inputText.value.match(mailformat))
{
alert("This is not an accepted email address");
return false;
}
}
First: Your validateBadEmail function is missing a return instruction. Set one return value for either IF case.
EDIT
Second: Validating input data must be done in the onsubmit event handler of the containing FORM. Handling onclick events in the input controls won't prevent the form being sumbitted.
I have a page which calls an external library, this library adds a payment form:
<form name="multipay_form" onsubmit="private_payment_send(); return false;">
....
</form>
I can not change any code here. I need to call a function after form is submitted. What I have done is:
jQuery('form[name="multipay_form"]').on('submit', function() {
alert("myfunction");
});
Which works ok, but there is one exception, the method "private_payment_send()", does form validation, I need to know if their function returned true or false, to be able to trigger my function or not.
Is this possible?. I want to avoid doing the validation again on my end, since if they add new field or any new rule I would have to do the same on my code, which is not optimal. Any ideas?
Is there a way to unattach the function from the form through javascript?, in that way I can call private_payment_send() from my function
<form name="multipay_form" onsubmit="private_payment_send(); return false;">
<button type="submit">test</button>
</form>
document.getElementsByName("multipay_form")[0].setAttribute('onsubmit','');
This will make it so the onsubmit is removed from the form without touching the HTML
Try to use done() function in Jquery
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
Following is Jquery documentation
https://api.jquery.com/deferred.done/
You can trigger your function only when the called function, here "private_payment_send" has returned true. This can be done like this
<form name="multipay_form" onsubmit="if (private_payment_send()) { alert("myFunction") }; return false;">
...
</form>
If you only want to use the jQuery part, you can completely remove the onSubmit attribute and only assign the submit handler using jQuery
jQuery('form[name="multipay_form"]').on('submit', function() {
if (private_payment_send())
alert("myfunction");
return false;
});
I want a really simple thing to happen on my page, after the user submits the form, there must be a delay before the form is actually submitted, however it doesn't seem to work html form:
<form action='index.php' method='get'>
<input type='submit' value='Reset' name='resetBtn' onClick='PreSubmit(this.form)'>
</form>
javascript function:
function PreSubmit(form) {
var func = function () {
form.submit();
}
setTimeout(func, 10000);
}
so I am really really new to javascript, but how I see it, onlick event must call this javascript function, it should wait 10 seconds and only then submit the form and update the page, however the form is submitted right away, why? and how do I make it wait before submitting? any kind of help would be appreciated
You need to stop the default behavior of the submit button. Lot's of folks make the mistake of returning false to do this, but that's not quite right and it's important to understand what returning false is doing. This isn't the best way (unobtrusive JS is a whole different subject), but to accomplish what you want with minimal changes do something like the following
HTML:
<form action='index.php' method='get'>
<input type='submit' value='Reset' name='resetBtn' onClick='PreSubmit(event, this.form)'>
</form>
JS:
function PreSubmit(event, form) {
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
var func = function () {
form.submit();
}
setTimeout(func, 10000);
}
add return to onclick.
onClick='return PreSubmit(this.form)'>
And add return false to PreSubmit.
function PreSubmit(form){
....
//this will stop the click event
return false;
}
So PreSubmit return false -> onClick return false, which will stop the submit button action.
http://jsfiddle.net/KVsQ4/
I think there's another problem you would consider, what'll happen if the user continuously click the button. wait another 10 secs(which means you should clearTimeout the previous timeID), or just disable it when the user click it the first time.
You need to make it a type="button", not a type="submit"
There are a few similar questions to this but none quite the same.
I want to know if there is an event that can be used to execute some JS before a page is submitting (i.e. POSTed).
Something like this?
<form onsubmit="do_something()">
function do_something(){
// Do your stuff here
}
If you put return like the code below, you can prevent the form submission by returning false from the do_something() function.
<form onsubmit="return do_something()">
function do_something(){
// Do your stuff here
return true; // submit the form
return false; // don't submit the form
}
If you are working with the form, you can use onsubmit event.
Using jQuery you can do that with
$('#myform').submit(function() {
// your code here
});
You can bind an event handler to the submit event (following code assumes you have an id on your form):
document.getElementById("someForm").onsubmit = function() {
//Do stuff
};
Yes, you can use on the onsubmit event on your form.
In pure HTML (without jQuery), you can use:
<form onSubmit="mySubmitFunction()">
...
</form>
More details here: https://www.w3schools.com/jsref/event_onsubmit.asp
The following code will abort the submission from the window level, which will not submit the form.
window.onsubmit = function() { alert('aborting submit'); return false; };
Tested with IE11, so it should work for some legacy applications without jQuery.