0

Why i get this error? I'm using window.onload, i don't understand ... Can you help me?

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Pràctica DOM3</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
        <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
        <script type="text/javascript" src="script.js"></script>
        <style>
            h2 {
                text-align: center;
                border-bottom: 1px solid black;
                padding-bottom: 20px;
                /*text-decoration: underline;*/
            }
            #ultimsEstudisCursatsLabel {
                margin-top: 10px;
            }
            #submitFormButton {
                margin: auto;
                display: block;
            }
            #resetFormButton {
                margin: auto;
                display: block;
            }
            meter {
                margin: 0 auto 1em;
                width: 100%;
                height: .5em;
            }

            meter[value="1"]::-webkit-meter-optimum-value { background: red; }
            meter[value="2"]::-webkit-meter-optimum-value { background: yellow; }
            meter[value="3"]::-webkit-meter-optimum-value { background: orange; }
            meter[value="4"]::-webkit-meter-optimum-value { background: green; }

        </style>
    </head>
    <body>

        <div class="container">
            <h2>Inscripció CF Informàtica Marianao</h2>
            <br>
            <form method="post" action="#" id="formulari">
                <div class="form-group">
                    <label class="control-label col-sm-2" for="input1">Nom</label>
                        <div class="col-sm-10">
                            <input type="text" name="nom" class="form-control" id="inputNom" placeholder="Escriu el teu nom ..." />
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Primer cognom</label>
                        <div class="col-sm-10">
                            <input type="text" name="primerCognom" class="form-control" id="inputCognom1" placeholder="Escriu el primer cognom ..." />
                            <br />
                        </div>
                </div>

                <div class="form-group">
                <label class="control-label col-sm-2">Segon cognom</label>
                    <div class="col-sm-10">
                        <input type="text" name="segonCognom" class="form-control" id="inputCognom2" placeholder="Escriu el segon cognom ..." />
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Data naixament </label>
                        <div class="col-sm-10">
                            <input type="date" name="dataNaixement" class="form-control" id="inputNaixament" placeholder="Selecciona la teva data de naixament ..."/>
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Email </label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="inputEmail" placeholder="Escriu el teu correu electrònic ..."/>
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Telèfon</label>
                        <div class="col-sm-10">
                            <input type="tel" name="telefon" class="form-control" id="inputTelefon" placeholder="Escriu el teu telèfon ..."/>
                            <br />
                        </div>
                </div>

                <div class="form-group">

                    <label class="control-label col-sm-2">DNI</label>
                        <div class="col-sm-10">
                            <input type="text" name="dni" class="form-control" id="inputDni" placeholder="Escriu el teu DNI ..." />
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="form-label col-sm-2">Cicle formatiu</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="cicleFormatiu">
                                <option value="smx">SMX: Sistemes Microinformàtics i Xarxes</option>
                                <option value="asix">ASIX: Administració de Sistemes Informàtics en Xarxa</option>
                                <option value="dam">DAM: Desenvolupament d'Aplicacions Multiplataforma</option>
                                <option value="daw">DAW: Desenvolupament d'Aplicacions Web</option>
                            </select>
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2" id="ultimsEstudisCursatsLabel">Últims estudis cursats</label>
                        <div class="col-sm-10">
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="eso" class="custom-control-input">ESO</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="batx" class="custom-control-input">Batxillerat</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="cfgm" class="custom-control-input">CF Grau Mitjà</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="cfgs">CF Grau Superior</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="altres">Altres</label><br><br>
                            </div>
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Usuari</label>
                    <div class="col-sm-10">
                        <input class="form-control" type="text" id="inputUsuari" name="usuari" />
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Contrasenya</label>
                    <div class="col-sm-10">
                        <input type="password" id="password" name="contrasenya" class="form-control" />
                        <meter max="4" id="password-strength-meter"></meter>
                        <p id="password-strength-text"></p>
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Torna a escriure la contrasenya</label>
                    <div class="col-sm-10">
                        <input type="password" name="contrasenyaCheck" id="contrasenyaCheck" class="form-control" disabled/>
                        <meter max="4" id="password-strength-meter"></meter>
                        <p id="password-strength-text"></p>
                        <br />
                    </div>
                    <br />
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Observacions</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" name="observacions" id="textarea" maxlength="500"></textarea>
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Termes i condicions</label>
                    <div class="col-sm-10">
                        <label class="checkbox-inline"><input type="checkbox" name="termesCondicions" value="yes" class="form-check-input" >Consulta <span><a href="condicions.html" target="_blank">aquí</a></span> els termes i condicions.<br></label>
                        <br />
                        <br />
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <input type="submit" value="Submit Form" class="btn btn-success" id="submitFormButton">
                </div>
                <div class="form-group">
                    <input type="reset" value="Reset Form" class="btn btn-primary" id="resetFormButton">
                </div>
            </form>

        </div>
    </body>
</html>


JS:

function main (){

    var inputNom = document.getElementById("inputNom").addEventListener("blur", validarNomCognoms);
    var inputCognom1 = document.getElementById("inputCognom1").addEventListener("blur", validarNomCognoms);
    var inputCognom2 = document.getElementById("inputCognom2").addEventListener("blur", validarNomCognoms);
    var inputNaixament = document.getElementById("inputNaixament").addEventListener("blur", validarData);
    var inputEmail = document.getElementById("inputEmail").addEventListener("blur", validarEmail);
    var inputTelefon = document.getElementById("inputTelefon").addEventListener("blur", validarTelefon);
    var inputDni = document.getElementById("inputDni").addEventListener("blur", validarDni);
    var inputUsuari = document.getElementById("inputUsuari").addEventListener("blur", validarUsuari);
    var password = document.getElementById("password").addEventListener("blur", validaContrassenya);




    // Recuento de carácteres en el text area.

        var textAreaID = document.getElementById("textarea");
        var length = textAreaID.getAttribute("maxlength");
        var textAreaCount = document.getElementById("count");
        textAreaCount.innerHTML = length + " caràcters restants.";
        textAreaID.addEventListener ("keypress", function () {
            document.getElementById("count").innerHTML = (length - this.value.length) + " caràcters restants.";
        });

    // Barra de seguridad METER.

    document.addEventListener("keydown", function () {
        var strength = {
            0: "Molt feble.",
            1: "Feble.",
            2: "Acceptable.",
            3: "Forta.",
            4: "Molt forta."
        }

        var password = document.getElementById('password');
        var meter = document.getElementById('password-strength-meter');
        var text = document.getElementById('password-strength-text');

        password.addEventListener('input', function() {
            var val = password.value;
            var result = zxcvbn(val);

            meter.value = result.score;

            if(val !== "") {
                text.innerHTML = "<strong>" + strength[result.score] + "</strong>";
            }
            else {
                text.innerHTML = "";
            }

            if (meter.value >= 2) {
                document.getElementById("contrasenyaCheck").disabled = false;
            }
            else {
                document.getElementById("contrasenyaCheck").disabled = true;
                document.getElementById('contrasenyaCheck').value = "";
            }
        });
    });

    // VALIDACIONES.

        // Primera validación.

            function validarNomCognoms () {
              var pattern = /^[a-zA-Z]*$/;
              if (this.value.length > 0) {
                if(!this.value.match(pattern)) {
                  this.setCustomValidity("No pot contindre números!");
                  this.reportValidity();
                }
                else {
                  this.setCustomValidity("");
                }
              }
              else {
                this.setCustomValidity("No pot citear buit ");
                this.reportValidity();
              }
            }

          // Segunda validación.

          function validarData () {
            if (this.value != "") {
              var dataRecibida = this.value;
              dataRecibida = dataRecibida.split("-").reverse().join("-");

              // Obtener la fecha actual.
              var today = new Date();
              var dd = today.getDate();
              var mm = today.getMonth() + 1;

              var yyyy = today.getFullYear();
              if (dd < 10) {
                dd = '0' + dd;
              }
              if (mm < 10) {
                mm = '0' + mm;
              }
              var today = dd + '/' + mm + '/' + yyyy;

              if (dataRecibida > today) {
                alert ("Data incorrecta.");
              }
              //this.value.setCustomValidity("");
            }
            else {
              alert ("citeá vacío.");
            }
          }

        // Tercera validación.

        function validarEmail () {
          if (this.value != "") {
              var emailPattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
              if (emailPattern.test(this.value)) {
                return;
              }
              else {
                alert ("Mail incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Cuarta validación.

        function validarTelefon () {
          if (this.value != "") {
              var emailPattern = /^\d{9}$/;
              if (emailPattern.test(this.value)) {
                return;
              }
              else {
                alert ("Telèfon incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Quinta validación.

        function validarDni () {
          if (this.value != "") {
              var emailPattern = /^\d{8}[A-Z]$/;
              if (emailPattern.test(this.value)) {
                  var lletres = ['T', 'R', 'W', 'A',
                                 'G', 'M', 'Y', 'F',
                                 'P', 'D', 'X', 'B',
                                 'N', 'J', 'Z', 'S',
                                 'Q', 'V', 'H', 'L',
                                 'C', 'K', 'E', 'T'];

                  var index = this.value % 23;

                  var my_array = this.value;
                  var last_element = my_array[my_array.length - 1];
                  var boolean = false;

                  for (var i = 0; i < lletres.length; i++) {
                    if (last_element == lletres[i]) {
                      boolean = true;
                    }
                  }
                  if (boolean) {
                    return;
                  }
                  else {
                    alert ("Lletra DNI incorrecte.");
                  }
              }
              else {
                alert ("DNI incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Sexta validación.

        function validarUsuari () {
          if (this.value != "") {
            if (this.value.length < 5) {
              alert ("Longitud mínima de 5 caràcters.");
            }
            else if (this.value.length > 12) {
              alert ("Longitud màxima de 12 caràcters.");
            }
            else {
              return;
            }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Seéptima validación.

        function validaContrassenya () {
          var meter = document.getElementById('password-strength-meter');
          if (meter.value < 2) {
            document.getElementById("cite9").style.display = "block";
          }
          else {
            document.getElementById("cite9").style.display = "none";
          }
        }
}
window.onload = main;

Thanks guys!!

ERROR: enter image description here

3
  • innerHTML is never null, please show the exact error message. Also, please reduce the code, we don't need all of it to solve the problem. Commented Feb 14, 2020 at 16:13
  • There you see, the error message says, that you're trying to read innerHTML from an element which does not exist. Commented Feb 14, 2020 at 16:15
  • 1
    Here: document.getElementById("count") returns null, because the HTML doesn't contain an element with id of count. Commented Feb 14, 2020 at 16:18

1 Answer 1

1

You never defined an element with id="count". Just check.
Also, when you define it, make sure it is a direct child of the body. You may try not to do this, but sometimes errors are caused.

Hope you understand now!

Sign up to request clarification or add additional context in comments.

10 Comments

"make sure it is a direct child of the body" Why??? document.getElementById can find an element even from your pocket, the element can be placed anywhere in the document, even into the head section.
@Teemu Sometimes, not having it as the direct child of the body can cause problems, so you access it this way: document.getElementById("direct_child").getElementById("indirect_child"). To avoid problems like this happening, I simply suggested that.
That's invalid HTML, ids should be unique within the document. If you for some odd reason must include multiple same ids, you can get the elements with document.querySelectorAll('[id="direct_child"]'), which will return a collection of the found elements.
@Teemu May I remind you that "direct_child" and "indirect_child" are not the same. But yes, your code seems valid except that ids are unique so you should only have one element, so using querySelector is much more appropriate than querySelectorAll.
Indeed, they're not the same. But the comment still stands, an element with an id within another element with an id is not a problem to gEBI at all. You can always get the correct element just by using document.getElementById('indirect_child'), no matter how deep in the DOM tree the queried element was.
|

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.