Forms Validation
To handle the activity in the input:
var choose = document.querySelector('#choose'); //choose is the id of the input
choose.addEventListener("input", function(){ //listening to input event (typing in the input)
console.log('input!!!!') //the action that will happan when typing
});
to handle other objects in the form according to the status of the input
var choose = document.querySelector('#choose'); //the input field
var errorSpan = document.querySelector('.error'); //the selector defining the error label
var btn = document.getElementById("myButton"); //the button
choose.addEventListener("input", function(){
if ((choose.value === "banana" ) || //
(choose.value === "cherry" )) // will accept only these options
{
errorSpan.style.display = 'none'; //do not display the error label
btn.disabled = false; //make the button active
} else {
errorSpan.style.display = 'inline'; //display the error label
btn.disabled = true; //make the button disabled
}
});
the error message can be added in JavaScript, will not appear on load
errorSpan.innerHTML = 'error msg'; //to fill in error
//and
errorSpan.innerHTML = ''; //to clear
to eliminate validation of of the form,
add the novalidate attribute
< form novalidate action="http://httpbin.org/get" method="get" >
To add a submit function in JavaScript
var frm = document.querySelector('form'); //handle the form element
frm.addEventListener('submit', function(e) { //calling the submit action, e stands for the event
handleSubmit(e); //call an action from a function
});
function handleSubmit() { //function to run
e.preventDefault(e); //do not execute the original submit action from the form action
alert('SUBMIT');
}
Full solution
html
css
var frm = document.querySelector('form'); //handling the form
var choose = document.querySelector('#choose'); //handling the input
var errorSpan = document.querySelector('.error'); //handling the error msg.
var btn = document.getElementById("myButton");
choose.addEventListener("input", function(){
showError();
});
frm.addEventListener('submit', function(e) {
handleSubmit(e);
});
function handleSubmit(e) {
if (choose.value === '') {
e.preventDefault();
showError();
}
}
function showError(){
if (choose.value !== '' ) {
errorSpan.innerHTML = '';
} else {
errorSpan.innerHTML = "Please enter your food";
}
}
back to main page