Reputation: 5
i've some trouble with this event listener. I'm tryng to add an event listener in the submit button, but it doesn't work. I don't know what I'm doing wrong! This is my work:
const form = document.getElementById("form");
form.addEventListener('submit', (e) =>{
let valid = true;
valid=valida();
if(!valid){
e.preventDefault();
}
});
function valida() {
var nome = document.getElementById("nome");
const nomeVal = nome.value;
var cognome = document.getElementById("cognome");
const cVal = cognome.value;
let valida = true;
valida = nomeVal.length < 8 ? setError(nome, "devi inserire nome"): setSuccess(nome);
if (cVal.length < 8) {
valida = setError(cognome, "devi inserire cognome");
}
return valida;
}
function setError(input, m) {
input.className = "error"
const ciao = input.nextElementSibling;
ciao.innerText = m;
return false;
}
function setSuccess(input) {
input.className = 'success';
const error = input.nextElementSibling;
error.innerText = '';
return true;
}
<form id="form" name="registrazione" action="index.html" >
Nome: <input id="nome" name="nome" type="text"> <small></small><br>
Cognome: <input id="cognome" name="cognome" type="text"> <small></small>
<br>
<button id="button" type="submit">Submit</button>
</form>
Upvotes: 0
Views: 166
Reputation: 310
I pasted your code into js fiddle. There was a \u200b hidden character at the end of the 2nd line. Once I removed that it looks like it worked. https://jsfiddle.net/mightypie/b1dmgtw2/9/
form.addEventListener('submit', (e) => {
Upvotes: 1
Reputation: 9
Hi have you tried using onclick event handler?
Place the onlclick event in your submit button
<form id="form" name="registrazione" action="index.html" >
Nome: <input id="nome" name="nome" type="text"> <small></small><br>
Cognome: <input id="cognome" name="cognome" type="text"> <small></small>
<br>
<button id="button" onclick="test()" type="submit">Submit</button>
</form>
then on your js you can use the below code:
function test() {
let valid = true;
valid=valida();
if(!valid){
e.preventDefault();
}
};
Upvotes: 0