Code is not working and I can’t seem to figure out why. I have to keep the javascript in the html head because it is required and I believe that’s where im going wrong and it’s not loading properly.The window onload is something new for me and i’m not sure if that would be the correct way to use it
___Javascript___ window.addEventListener("load", init); function validation(){ var userNme = document.getElementById("username").value; var pass = document.getElementById("password").value; var id = document.getElementById("student-id").value; var success = false; var words = /^[A-Za-z]+$/; if(userNme.match(words)){ document.getElementsByClassName("one").setAttribute("class", "hidden"); success = true; } else{ document.getElementsByClassName("one").setAttribute("class", "visible"); } if(pass.match(/[a-z]/) && pass.match(/[A-Z]/) && pass.match(/[0-9]/)){ document.getElementsByClassName("two").setAttribute("class", "hidden"); success = true; } else{ document.getElementsByClassName("two").setAttribute("class", "visible"); } if(id.length == 9){ document.getElementsByClassName("three").setAttribute("class", "hidden"); success = true; } else{ document.getElementsByClassName("three").setAttribute("class", "visible"); } } function init(){ var start = document.getElementById("go"); start.addEventListener("click", validation); } __HTML__ <input type="text" placeholder="Username" id="username" required> <div class="one hidden"> Username needs to contain only letters </div> <input type="password" id="password" placeholder="Password" required> <div class="two hidden" id="Pword"> Password needs to have at least one capital letter, one lower case, and one number </div> <input type="text" id="student-id" placeholder="Student id"> <div class="three hidden"> Student ID has to be exactly 9 numbers </div> <div class="four"> <textarea id="textarea" name="message" placeholder="Enter text here" cols="22" rows="10" maxlength="25" onkeyup="myFunction()"></textarea> <span style="color: red;" id="counter">25</span> <span style="color: black;">words remaining</span> </div> <input type="button" value="Submit" placeholder="Submit" id="go" onclick="init()" >
Advertisement
Answer
It is because not all the elements are mounted on the DOM if <script>
is in <head>
. You use <script>
in <head>
when you want javascript to execute independent of the elements to be mounted.
If your <script>
tag is trying to modify objects from DOM
, you have to wait for the element to be mounted first.
Edited:
Fix 1:
Keep <script>
tag below those elements. You can also use all these javascript on another file and then <script src="path/to/js">
below all the elements that are used in the script.
Fix 2:
If you want to keep it in head, use load
eventListener on <body>
and then execute all these code. Instead of window.addEventListener("load", init);
use body.addEventListener("load", init)
.