How to make work on submit function in Javascript? - 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).

Related

JS Page won't redirect using location.href?

I'm learning Javascript, and this basic redirect isn't doing anything.
The alert fires, but no version of 'page redirect' code I've tried seems to be working.
I've tried every version of location.href, document.location.href, window.location, etc etc....
I just want to switch urls when user input == '85.5'. But despite hours of trying, it just won't work.
What am I missing here?
Thanks!
I'm calling this function in a form element like so:
<form onsubmit="showInput()">
<input type="text" id="question" name="inputz">
</form>
function showInput(){
var InputNumber = document.getElementById("question").value;
if(InputNumber == '85.5'){
alert("You escaped"); //this works
alert(InputNumber); //this works
window.location.href ='/Survive_The_Swamp3.html'; //this does NOT work
return false;
}
else {
alert(InputNumber);
document.location.href ="https://i.redd.it/twrza9clfsh21.jpg"; //also doesn't work
return false;
}
}
This has nothing to do with window.location.href.
You don't have anything that submits the form. So the onsubmit handler is never called.
Forms are submitted when there's an <input type="submit"> which will be rendered as a button. Forms can also be submitted if there's a <button> inside the form. If neither of these exist then the form is never submitted unless you manually submit the form by calling the form's .submit() method in javascript.
For your code to trigger you need to wait for the <input> change event:
<input type="text" id="question" name="inputz" onchange="showInput()">
However there is a subtle issue with how onchange events work. They are triggered BEFORE the input gets the new value. As such when your user type "85.5" your event handler will see "85.". To get the current value you need to read it from the event object:
function showInput(event){
var InputNumber = event.target.value;
//...
The reason onchange works this way is to allow you to cancel the event thus preventing the <input> from getting the value. For example you can use this feature to prevent the user from entering something that is not a number.
I appreciate the feedback and information from everybody; however the only thing I was able to finally get to work was using the following configuration:
<form onsubmit="showInput(); return false"> //maybe return false here made the difference?
<input type="text" id="question" name="inputz" >
</form>
function showInput(){
var InputNumber = document.getElementById("question").value;
if(InputNumber == '85.5'){
alert("You escaped");
window.location.href='/Survive_The_Swamp3.html';
}

on Submit add input to form than submit the updated form vanilla js

I have a form with onsubmit='ConsolidateRTFEdits(event)'
and the function is as follows:
function ConsolidateRTFEdits(event){
event.preventDefault()
const editor_fields = document.querySelectorAll( '.ckeditor-widget' );
const form = event.target;
editor_fields.forEach(field => {
input = document.createElement("input");
input.setAttribute('type', "hidden")
input.setAttribute('name', field.dataset.ck)
input.setAttribute('value', field.ckeditorInstance.getData())
form.append(input)
})
form.submit()
I can successfully log the form with added input, as well as see it updated on the DOM, however form.submit() submits the form without the appended attribute.
What am I doing wrong?
How to sumit the updated form?
I have also tried to add an id and document.getElementById() the same form afterwards, but does not work either.
You are already overriding the submit handler, my recommendation is to find a better way to achieve what you need. if it's not possible, I can suggest three approaches to get it fixed:
After manipulating your form, do the submission logic manually from JavaScript
Or, use addEventListener and removeEventListener, to add a custom handler and remove it before re-triggering the event
const formElement = document.forms['myForm'];
formElement.addEventListener('submit', customHandler);
function customHandler(e) {
e.preventDefault();
//....
formElement.removeEventListener('submit', customHandler);
formElement.submit();
}
<form name="myForm" id="myForm">
<input type="text">
<button type="submit">Submit</button>
</form>
from comments above, change the button type to be button not submit, and add the needed logic to its onclick handler, then trigger submitting the form!

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();
});

Run javascript onsubmit before browser checks form

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>

Categories

Resources