I know a way to stop a form from submitting, but i have a on click event to the submit button and its firing even though the form doesnt pass the HTML validation.
<form id="signupform" class="signupform" onsubmit="(e)=>{e.preventDefault()};return false">
</form>
My goal is to stop the page refresh either way (if it validates or not) but still allow the built in validation to run first.
Any suggestions?
A submit button's job is to trigger the submit event of a form. Therefore, with form elements, you don't set up click events on the submit button, you set up submit event handlers on the form.
Then, to introduce validation into the mix, you can stop the native submit to take place in the handler, only if validation fails. This is done by accessing the event argument that is automatically sent to every DOM event handler* (see next paragraph for caveat). You can use the event.preventDefault() method to stop the native event from taking place.
*One final note, the use of inline HTML event handling attributes such as onsubmit and onclick is to be avoided. This is a 25+ year old technique that we used before we had standards and unfortunately, because they seem easy to use, they get copied by new developers who don't know any better. There are real reasons not to use them and you've stumbled into one. Your e argument to your event handling function is not being populated with a reference to the event like you think it is. That only happens when you use the modern standard way of setting up event callbacks, which is .addEventListener().
// Set up a submit event handler for the form
// not a click event handler for the button because
// clicking a submit button triggers the form's submit event
document.querySelector("form").addEventListener("submit", function(event){
if(document.querySelector("input").value === ""){
// Invalid data! Stop the submit!
event.preventDefault();
alert("Please fill in all fields!");
return;
}
// If the code reaches this point, validation succeeded
console.log("Form submitted");
});
<form action="https://example.com" method="post">
<input>
<button>Submit</button>
</form>
Related
I've a form with few textfields and a submit button. A submit handler is attached to the form in order to validate the form before submission. Additionally, the handler is supposed to show an OK message to the user, and finally to redirect to the front page.
Validation works fine, but when the validation succeeds, the OK message is shown only briefly or not at all, and the page is refreshed instead of redirection.
Here is the form:
<form id="form" method="post">
<input name="firstname">
<input name="lastname">
<input type="submit" value="Submit">
</form>
<div class="hidden v-ok">Validation OK</div>
<div class="hidden v-failed">Validation failed</div>
And the related JS:
const form = document.querySelector('#form');
form.addEventListener('submit', e => {
const controls = Array.from(form.elements),
valid = controls.every(control => control.value !== '');
if (!valid) {
// Validation failed, don't submit
e.preventDefault();
// Show ValidationFailed message
const message = document.querySelector('.hidden.v-failed');
message.classList.remove('hidden');
return;
}
// Validation OK, show message and submit
const message = document.querySelector('.hidden.v-ok');
message.classList.remove('hidden');
window.setTimeout(() => {
window.location.href = '/';
}, 2000);
});
I've also tried to redirect without the timeout, but the result is the same, the page is only refreshed, it never navigates to the front page. What can I do to get my form posted and still able to see the message and do the redirection?
TL;DR; Showing the message and redirecting later provides the document location to stay on the current page. You can't submit a form and stay on the current page. Use AJAX aka XMLHttpRequest to send the data to your server instead of submitting a form.
How HTMLFormElement works
On early days, before JavaScript existed, form element was purposed to send data from a page to a server, then the server handled the data, and responded with a new page, which was loaded by the browser. Even today, browsers are doing exactly this same when a form is submitted.
The standard says:
"The form element represents a hyperlink that can be manipulated through a collection of form-associated elements" (emphasis mine).
Now, if you're not interested in a deeper explanation of how the form submission works under the hood, you can scroll down to the All this in practice chapter.
But what actually happens when a submit button is clicked? The standard defines a Form submission algorithm, which is very deeply detailed, and is a bit hard to follow. Here are the strongly simplified main steps:
Browser checks whether the form can be submitted (document fully active, sandboxing etc.), failing the check cancels the algorithm
Validation defined by the elements' attributes is executed, if validation fails the algorithm is cancelled
The attached submit event(s) are executed (attached event(s) can fire only once)
If any of the submit handlers called event.preventDefault the algorithm is cancelled
The encoding of the form is set
An entry list of the form control elements is created
Various attributes of the form are parsed (ex. action defaults to the URL of the form's document if the attribute is not set)
The internal sending method is selected based on method attribute of the form (defaults to GET) and the schema of the URL in action attribute
A navigation plan is created (a task) and send to the event queue (includes the deformed form data)
The task in the event queue is executed, and navigation to a new page takes place
In the real algorithm, a lot more of actions are executed, ex. step 1 is executed between many of the steps, and the algorithm prevents concurrent submissions. Also, the described algorithm stands only when an actual submit button is activated. If the submission is called via JS by form.submit method, steps 2 - 4 are jumped over.
The above algorithm explains how JS form validation in submit event handler can cancel the submission (#4). The unload document process (#10) explains how the timeout is broken when a new page is about to load (all the pending timers and events are aborted). But, any of these doesn't actually explain, how location.href in a submit event handler is ignored without the timeout.
The answer to this question is hidden in the definition of the form: It "represents a hyperlink". Activating a hyperlink sets a specific internal navigation event, and an internal "ongoing-navigation" flag. Any later activation of any hyperlink checks that flag, and is cancelled if the flag was set. Setting location.href is not actually a hyperlink, but it uses the same navigation mechanisms, hence it's also cancelled, if a pending navigation is detected. It's notable, that calling event.preventDefault in a submit handler unsets the "ongoing-navigation" flag immediately, which makes setting location.href to work again later in the handler.
(The navigation behavior described above is heavily simplified. To fully understand how the browser navigation works, provides deep knowledge of the event queues and navigation process, which are described in the standard (details being even partially implementation-dependent), but these are not the objective of this answer.)
All this in practice
As the most of the previously described actions of HTML Form are executed under the hood, how can this all be applied in the point of the view of a programmer? Let's make a synthesis (without specific rationales).
<form> is a link which can send more information to the server than a regular link like <a>
action attribute of a form is roughly equal to href attribute of a regular link
Submitting a form always loads a new page, this is the default action of the submission
Any attempt to navigate to another page (including clicking links or submitting other forms, or setting location.href in JS) is prevented while a submit event is pending
Programmer can interfere form submission by setting a submit event listener to the form
If attribute-based form validation fails, attached submit event handler(s) is/are not executed
A submit event handler can modify the current page and the data to submit, and it also can cancel the form submission
Nevertheless what is done in a submit event handler, the form is submitted when the handler execution is finished, unless the handler cancels the default action of the submit event
What triggers a form submission then? There are multiple ways to start a form submission. All the elements below are so called submitter elements, those have "submit the form" as their default action:
<input type="submit" value="Submit">
<input type="image" alt="Submit">
<button type="submit">Submit</button>
<button>Submit</button>
Hitting ENTER on active <input type="date/number/password/search/tel/text/time/url/week">
Calling form.submit method in JS
Notice the typeless <button> element, it's also a submit button by default, when placed inside a form.
Preventing the default action of an event
Some events have a default action, which is executed after the event handler function has finished. For example, the default action of submit event is to submit the form triggered the event. You can prevent the default action to be executed in the event handler by calling preventDefault method of the event object:
event.preventDefault();
event is either the object passed in the arguments of the handler, or the global event object.
Returning false from an event handler function doesn't prevent the form submission. This works with inline listeners only, when return false; is written in an onsubmit attribute.
The first three elements in the submitter element list above are "stronger" than the other elements. If you've attached a click listener to an input type of submit/image or a button type of submit, preventing the default action of the (click) event doesn't prevent the form submission. Other elements can do that also within a click listener. To prevent the submission in all cases, you've to listen to submit event on the form instead of clicks on the submitter elements.
And again: form.submit method called in any script, will jump over all form validations and won't fire any submit events, it can't be cancelled via JS. It's notable, that this stands for the native submit method only, ex. jQuery's .submit isn't native, and it calls the attached submit handlers.
Send data and stay on the current page
To send data and still stay on the current page can be achieved only by not submitting the form. There are multiple ways to prevent the submission. The simplest way is to not include a form in the markup at all, that makes a lot of extra work with data handling in JS, though. The best way is to prevent the default action of the submit event, any other way with a form would cause extra work, for example, triggering JS without a submitter element still provides detecting submissions made by #5 in the submitter elements list.
As the data won't go to a server without submitting, you need to send the data with JS. The technique to use is called AJAX (Asynchronous Javascript And Xml).
Here's a simple vanilla JS code example of sending data to the server, and staying on the current page. The code utilizes XMLHttpRequest object. Typically the code is placed in a submit event handler of a form, as it is in the example below. You can make a request anywhere in the scripts on a page, and if a submit event is not involved, preventing the default action is not needed.
form.addEventListener('submit', e => {
const xhr = new XMLHttpRequest();
const data = new FormData(form);
e.preventDefault();
xhr.open('POST', 'action_URL');
xhr.addEventListener('load', e => {
if (xhr.status === 200) {
// The request was successful
console.log(xhr.responseText);
} else {
// The request failed
console.log(xhr.status);
}
});
xhr.send(data);
});
The analogy to a form is scattered allover the code:
control element values are included in data (form being a reference to an existing form element)
method attribute is the first argument of xhr.open
action attribute is the second argument of xhr.open
enctype attribute is created by FormData constructor (defaults to "multipart/form-data")
The difference between AJAX and form submission is, that when getting a response for an AJAX call from the server, the JavaScript execution continues in the load handler of xhr instead of browser loading a new page when submitting a form. In that load handler you can do what ever you need with the data server sent as the response, or just redirect (also succesfully with a timeout). It's also possible to leave the load handler out of the code, when you don't need a notify of the request success/failure or any response data.
In modern browsers you can also use Fetch API to make an AJAX request. Also, most of the commonly used frameworks (if not all) and many libraries (like jQuery), have their own (more or less simplified) implementations for various AJAX-based tasks.
Remarks
Due to the order of the tasks executed in the internal submit algorithm, the validation attributes are handled before calling the submit event handler(s). If any of the validations fails, the algorithm is cancelled. This means, that when the form validation fails, also the submit event handler(s) are not executed.
Validation based on the validation attributes is executed only after activating a submitter element, validation attributes are not affecting to an object created by FormData constructor, which can be created at any time, a submit event is not necessarily needed.
The target attribute of the form is ignored when creating a FormData object. An AJAX call always targets to the current page, it can't be redirected to another document.
It's not mandatory to send a FormData object, you can send any data you need, but it has to be formatted according to the method of the request.
Here's the part of my form:
<form name='form-main' onsubmit='return validate()' action='' method='post'>
<center><input type='submit' onClick='this.disabled=true; this.form.submit();' value='I accept - Download the GM!'/></center>
</form>
and here's the validate function:
function validate()
{
// this is just to test if it actually shows
alert('You must not leave any of the fields blank!');
return false;
}
Whenever I hit the submit button, nothing happens, the page just reloads.. I would like it so it shows the alert dialog.
When you call the form's submit function, the submit event is not fired. This is by design, the assumption is that if you're triggering the submission from code, you've already done any necessary validation. (Note that this is true of the HTMLFormElement#submit function; it is not necessarily true of the wrappers libraries put around it.)
In your example, I would remove the click handler on the button. It's a submit button, so just put any relevant logic in the submit event on the form. Alternately, if you prefer, call validate() as part of the button's click.
You can override the original prototype "submit" method like this:
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = function (){
this._submit();
alert('Deddy Is Great :)'); // or fire the onsubmit event manually
};
The onclick event of your submit button is firing immediately before the onsubmit event of your form, and this is disabling subsequent events from propagating and firing, which causes the validate function to never get triggered. You can see this is you remove the this.disabled=true; from your code example.
Per the docs at W3:
A form control that is disabled must prevent any click events that are
queued on the user interaction task source from being dispatched on
the element.
You should remove the click event code from the submit button, and simply allow the function to do what you need it to do, including disabling the button. For example:
function validate() {
// this is just to test if it actually shows
document.getElementById('sub').disabled=true;
alert('You must not leave any of the fields blank!');
return false;
}
jsFiddle example
I am submitting a form using JQuery and an event listener bound to a div (not an input field) and I am trying to prevent multiple submits, so the customer does not get overcharged. I am trying to accomplish this by removing the submit-button class of the clicked div, so the next time the user clicks it, JQuery won't listen to the event that is associated with the submit-button preventing multiple submits.
Using the implementation below however, for some reason, does not prevent multiple submits, as intended.
HTML
<div class="submit-button button-style">Submit</div>
JQuery
$(".submit-button").click(function(){
$(this).removeClass("submit-button");
//**submit form**
});
NOTE: I must stick to a solution that uses the html above, so solutions using an input element of type submit, will not be useful.
I appreciate any suggestions on how to make this work. Many thanks in advance!
You can make use of .one() to prevent it from firing multiple times -
$(".submit-button").one('click',function(){
//**submit form**
});
http://api.jquery.com/one/
Edit :
In case of error :
function submitForm(){
//**submit form**
$.post('submit.php').error(function(){
// rebind event on error
$(".submit-button").one('click',submitForm);
});
}
$(".submit-button").one('click',submitForm);
You could use something like:
$('something').one('click', function(){
// submit code
});
Which will only fire once.
A significant portion of users don't bother clicking the submit button to submit a form - there's other more convenient ways, like hitting the enter key when the cursor focus is on a form field.
A more robust approach is to block the form via the forms submit event, and maintain a variable to keep track of the form submission state.
var submitted = false;
$("form#myForm").submit(function(evt){
if (submitted) {
evt.preventDefault();//stops form submission
return;
}
submitted = true;
});
I omitted form validation for this example.
I have a web form that uses a lot of JavaScript and ajax to determine if each field is valid. It gives warning messages on the fly to help the user know when there's a problem. I even use the "disable" feature on my submit button until everything is up to snuff. But here's the problem: All the event handling happens using the onblur feature. but when the last field is filled out, the validation doesn't happen till the user clicks away from that field. but why would they? there's nothing left to do on the page but click submit, which they can't do until they click somewhere else, anywhere else, first (to set off the validation event). I'm trying to find a way around this. There has to be a way where they don't have to make that extra click. it just doesn't seem professional. Is there a standard way around this? Can the validation event be triggered each time the user types an individual letter?
The form node has an onsubmit event that will fire when the user tries to submit the form. You can use this to validate all of the form fields and decide whether to let the user submit the form. The general implementation is this:
<form onsubmit="return validateForm()">
...
</form>
And in your JavaScript function, you have to return true if the user can continue submitting the form, or false to cancel the user's request before the form is submitted.
(In Psuedo-code):
function validateForm(){
if(formIsOkay){
return true;
}else{
return false;
}
}
You can validate each field using onkeyup, and withhold your user notification to the onblur method so it doesn't get annoying. If all fields are valid at the onkeyup, enable the submit button.
Given the limitations of {onChange, onKeyup, blur, etc} when it comes to handling copy/pasted or other edge cases I would probably add a timer to poll every 500ms or so and enable/disable the submit button:
window.setInterval(checkEnableSubmit, 500);
function checkEnableSubmit(){
if(validateForm()){
// enable submit button
}
}
function validateForm(){
if(formIsOkay){
return true;
}
return false;
}
I'd still call validateForm() on the button click to avoid users invalidating data and submitting before the timer is called. Server side validation is a given but I'd like to avoid the bad submit if possible.
I have a form where I've specified onSubmit="validate()", but I want to ignore the validation if the submit-button was clicked. Is there a good cross-browser way of detecting if the submit button was clicked and thus ignoring the validation?
Why don't you use a button instead of a submit, and set it's action on the click of the button? That way you can control if you want to validate, submit, or whatever else you like.
The submit event only fires if the form is submitted by the user; not if it is submitted via JS.
Therefore:
<input type="submit" onclick="this.form.submit(); return false;">
If JS is not available, this acts like a normal submit button … and the onsubmit still fails to fire as it also requires JS.
(Attaching events using JS instead of intrinsic event attributes is, as usual, preferred by excluded from this example for the sake of clarity)
you can try to use a <input type="button"... with an onClick that submits the form - a javascript .submit() doesn't fire the onSubmit-function of the form.
Did you try this?
<input type="submit" onclick="void(window.validate=function(){return true;})" value="Submit" />
Just return false, or preventDefault from your submit button handler