Run javascript onsubmit before browser checks form - javascript

I have a form with a billing-address and a shipping-address.
These addresses have some fields with the "required" attribute.
If a checkbox "use billing as shipping" is checked, the billing adress should be copied to shipping onSubmit.
But when I click submit, at least chrome does its checks and complain about a field being empty, and halts the submitting before my copy_billing_to_shipping can run.
Is there a "hook" on submit which runs before browser validates?

You could replace your submit button by a simple button, like this:
<input type="button" onclick="myOwnValidate(this)" />
and then, if everything is ok in your validate method, submit the form:
myOwnValidate = function(input) {
...
if(valid) {
input.form.submit();
}
};

Some folks like to add a "click" handler to buttons on the form to trigger validation. This is not ideal because users can submit forms by pressing the enter key when focused in a text input. This would bypass form validation.
The better way to do this is to add an event listener for the "submit" event on the form. Your event handler function should return true or false. If true, the form will be submitted.
Just be sure not to have any javascript bugs in your event handler, because if you do, the form will be submitted anyways.
<form id="myform">
....
</form>
<script>
function validate(e) {
var isValid = ...; // Some logic to determine validity.
return isValid;
}
document.getElementById("myform").addEventListener("submit", validate);
</script>

Related

How to make work on submit function in Javascript?

Ayo,
I'm a bit struggling with functions in JS.
The idea is that after the user clicks submit button, it checks if all the required fields have been filled out and if yes, it will trigger the loading animation.
The loading animation is supposed to be a status indicator in the meanwhile of sending the form and redirection to the success page.
I tried to use the onsubmit function in the form HTML tag but that does not work. The important thing is that it will happen one if the required fields are filled out.
Thanks
JS
const submit_btn = document.querySelector('.submit-btn')
function loading() {
this.innerHTML = "<div class='loader'></div>"
}
HTML
<form
onsubmit="loading()"
action="https://formsubmit.co/2007080c2cf8bd2ebb68506e7aa98c5f"
method="POST"
enctype="multipart/form-data"
>
I tried to use the onsubmit function in the form HTML tag but that does not work.
In regards to validation:
You can use the Constrained Validation API (see MDN) to check if all fields have been filled. Usually you want to use it after the user has submitted the <form> but before the form is sent to the server.
This is achievable by using it inside an event handler that is called on submitting the form.
In regards to event handling:
To implement the mechanism described above, what you want to do is adding an event listener to the submit event of the form via .addEventListener() instead of the onsubmit attribute. This way you'll receive an event object as argument of the event handler function with which you can prevent the form submission.
Example:
const myForm = document.querySelector('form'); // or '#myform', etc...
// define the event handler function
function onFormSubmission(event) {
const fields = Array.from(event.target.elements);
const allValid = fields.every(field => field.reportValidity());
if (!allValid) {
event.preventDefault(); // stop form submission
return;
}
event.target.innerHTML = '<div class="loading"></div>';
}
// add an event listener that fires on submission
myForm.addEventListener('submit', onFormSubmission);
<form id="myform" action="path/to/backend/script.php" method="POST" enctype="multipart/formdata" novalidate>
<input type="text" name="foo" placeholder="I am required!" required>
<hr>
<button type="submit">Submit form</button>
</form>
EDIT
Sorry, I missed to add the part that displays the loading information/element. Added (although you won't really see it because if all required fields are filled, the form will be submitted which results in a page refresh. You'd need something like XHR or similiar but that's not the scope of the question).

Intercepting a submit not working

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

Keeping browser HTML form validation when submitting with javascript?

Is it possible to keep the default HTML validation if submitting via Javascript?
What I mean is that, if I submit a form using this JS method:
document.getElementById("mc-embedded-subscribe-form").submit();
How do I keep the defualt error messages thrown by the browser?
One workaround I thought of is using this:
<form onSubmit="return somefunction()">
But because the API returns the success inside a closure function, I can't use this method.
HTML5 has also specified a JS API that you can use to interact with forms/elements in regard to their validation status: https://www.w3.org/TR/html5/forms.html#the-constraint-validation-api
So the easiest way to achieve this would be to call the checkValidity method of your form, and only submit it when this returns true.
Something like this:
function submitIfValid() {
var form = document.getElementById("mc-embedded-subscribe-form");
if(form.checkValidity()) {
form.submit();
}
else {
//
}
}
and then you would just call that function when you want to trigger form submission.
according to my understanding of your question, html validation is not enough to halt submission, you have to validate required inputs in javascript too before submitting.
e.g
if (!empty(username)) {
document.getElementById("mc-embedded-subscribe-form").submit();
}
You do not need to use form.submit() ever. Do it properly (onsubmit), or use click() on the submit button.
Doing it properly...
I can't think of a good reason to automatically submit a visible form. To submit data without user-interaction use XMLHttpRequest or WebSockets.
A form is submitted by user interaction (e.g. pressing its submit button), so there is no need to use JavaScript to submit a form. It is more likely that you need JavaScript to prevent a form submission, by returning false in the onsubmit event handler.
...or use click()
To programatically invoke HTML5 validation (and also any JavaScript onsubmit event handlers attached to the form), you can call the click() function of a submit button that belongs to the form.
If the form has no submit button, you can create a temporary one:
var form = document.getElementById("mc-embedded-subscribe-form");
var button = document.createElement('input');
button.type = 'submit';
button.style.display = 'none';
form.appendChild(button);
button.click();
Forms with multiple submit buttons should each have name attributes so the server can detect which button the user clicked. You can 'click' these buttons using form.buttonName.click().
form attribute
this solution avoids javascript, let's say that #my-btn is a button outside the form #mc-embedded-subscribe-form, you could just set on it
<button id="my-btn" type="submit" form="mc-embedded-subscribe-form">Go!</button>
requestSubmit()
with vanilla javascript you could call requestSubmit()
const form = document.getElementById('mc-embedded-subscribe-form');
form.requestSubmit();
the hackish solution
you could put an hidden submit button in the form and then trigger the click event on it
<form id="mc-embedded-subscribe-form">
<button id="real-btn" type="submit" style="visibility: hidden"></button>
</form>
<button id="my-btn">Go!</button>
const btn = document.getElementById('my-btn');
const btn_real = document.getElementById('real-btn');
btn.addEventListener('click', (e) => {
e.preventDefault();
btn_real.click();
});

Chrome Extensions programming - cancelling a form submit

I have a chrome extension which is just a simple form with two input fields and a submit button. The problem I encountered is that something like this:
$('#submit').submit(function() {
$('#word').val('')
$('#translation').val('')
return false
})
Still reloads the popup.html (e.g. submits the form)! I was forced to change the type of the submit button to just 'button' and use
$('#submit').live('click', function(e) {
$('#word').val('')
$('#translation').val('')
})
This works, but now (of course) the ENTER doesn't work for form 'submission'... and I feel this is a hack when the original prevention of reload by returning false should work...
Anyone else had such a problem?
The .submit() is an event on the form, not on the submit button.
I.E.
<form onsubmit="return false;"></form>
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from the onsubmit event of the form.
$('#YOUR_FORM_ID').submit(function() {
$('#word').val('')
$('#translation').val('')
return false
})

How to implement search textbox as in stack overflow website?

I have a search textbox in the web page. When the user presses enter key after entering text in that textbox then the search function should get executed. How to do this?
Check the onkeypress event of this and look for the keycode 13. Once keycode 13 is hit fire a click of a hidden button and do programming on the back end of the event of that hidden button.
If there's only one input field in a form, then the form will submit when you press enter even if there's no 'Submit' button.
eg
<form action="/search">
<input type="text" value="search text">
</form>
will submit when enter is pressed.
If that is the only textfield in your form, then pressing enter causes the onsubmit handler to run. But that will submit the entire page. If you want to perform an ajax command onsubmit and not refresh the whole page, then make sure your onsubmit handler returns false.
To do a regular full page form submit when enter is pressed:
<form action="/doit">
<input type="text" value=""/>
</form>
To do an ajax form submit when enter is pressed, something like this jquery code could be used:
$("form").submit(function() {
$.ajax(...);
return false;
});
basically u can do it like this:
i like to use jquery for most javascript stuff for cross browsers compatibility.
$("#btnID").keypress(function(event){
//filter enter key only
if(event.keyCode == 13){
//do something here
}
return true;
});
I have implemented this functionality very easily! I have a search textbox and a button with style ="display:none". These controls are surrounded by an ASP panel, I have set DefaultButton property of the panel as the button's ID. Now on entering text and pressing enter key the search functionality present in the button click event gets executed and also the button is also not visible to the user's!!!

Categories

Resources