I need to create a form that contains the following; name, surname, email, telephone number. through javascript with a for loop I have to make sure that all the fields have been filled in and if not, write with an innerHTML "error" next to the missing field. I have to use 'document.forms [x]. [x]' and perform element checking through a 'for' loop. In the end, I have to enter the privacy consent through a checkbox to be selected compulsorily. If all fields have been entered according to the criteria required it must redirect to www.stackoverflow.com
This is the malfunctioning code
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Documento senza titolo</title>
<link href="base_css.css" rel="stylesheet" type="text/css">
<script src="convalida.js" type="text/javascript">
</script>
</head>
<body>
<label><strong>Compila il form</strong></label>
<form id="form1">
<label>Nome: </label>
<input type="text" name="name" id="name">
<br><br>
<label>Cognome: </label>
<input type="text" name="surname" id="surname">
<br><br>
<label>E-mail: </label>
<input type="email" name="email" id="email">
<br><br>
<label>N° Matricola: </label>
<input type="number" name="number" id="number">
<br><br>
<input type="checkbox" id="privacy" name="privacy" required> accept privacy condition
<input type="submit" onClick="controllo_convalida()">
</form>
</body>
</html>
function controllo_convalida(){
var controllo = false;
var i;
for (i = 0; i < (document.forms[0].elements.length)-1; i++) {
if (document.forms[0].elements[i].value == "" ) {
controllo = false;
alert("Compila tutti i campi del form!");
}
if (controllo == true) {
document.forms[0].action = "https://stackoverflow.com/";
document.forms[0].submit();
var x = document.getElementById("privacy").required;
document.getElementById("form1").innerHTML = x;
}
}
}
requiredin the html, and let the browser perform the validation?