1

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


3
  • 1
    is there a reason why you can't add the attribute required in the html, and let the browser perform the validation? Commented Dec 12, 2020 at 22:32
  • I have to follow the contents of the description Commented Dec 12, 2020 at 22:51
  • stackoverflow.com/questions/38233301/… Commented Dec 12, 2020 at 22:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.