-2

I am completely new to JavaScript, and I can't figure out why I'm getting this error: Uncaught TypeError: Cannot read property 'addEventListener' of null.

I followed the advice posted in response to a similar question and put the file containing my JavaScript in the bottom of my body, but that didn't fix it. I also tried making the button onclick=checkValidity(), but that didn't work either.

        document.getElementById("loginButton").addEventListener("click", 
        checkValidity);

        function checkValidity() {
            var usrName = document.getElementById("inputUsername").value;
            var usrPswd = document.getElementById("inputPswrd").value;
             if(usrName == "admin" && usrPswd == "123"){
                 window.open("HtmlPage2.html");
             }
             else {
                 alert("Your username and password are incorrect.");
                }
            }


    and the HTML:

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial- 
         scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <link rel="stylesheet" type="text/css" href="stylesheet.css">
            <title>Document</title>
        </head>
        <body>
            <div class=wrap>
            <input type="text" id="inputUsername">
            <p>Username</p>
            <input type="password" id="inputPswrd">
            <p>Password</p>
            <button id="loginButton">Log in</button>
            <p id="login"></p>
            </div>
            <script type="text/javascript" src="Script.js" async></script>
        </body>

        </html>

What I want the code to do is check whether the input in the inputUsername and inputPswrd match that specified in the if...else function, and if so, open a new window; otherwise alert an error message.

EDIT: If I move all the code above to the top of my JS file, it will work as intended and open a new window, but then the code for that new page won't run (but the new page code does run it's at the top of my JS file). The error message I get when the new window opens is line 1: Uncaught TypeError: Cannot read property 'value' of null at Script.js:1.

Additional code: JS for HTML page 2:

    document.getElementById("greeting").innerHTML="Welcome";

    document.getElementById("productButtonOne").addEventListener("click", 
    addToCart);
    document.getElementById("productButtonTwo").addEventListener("click", 
    addToCart);
    document.getElementById("productButtonThree").addEventListener("click", 
    addToCart);

    var clicks = 0;
    function addToCart() {
        clicks = clicks + 1;
        document.getElementById("cartProductsTotal").innerHTML = "You have " + 
        clicks + " items in your shopping cart.";
        }

Beginning of HTML for page 2:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" type="text/css" href="stylesheet.css">

        <title>Document</title>
        </head>
        <body>
        <div class=wrap>
        <h1 id="greeting"></h1>

        <div id="productOne" class="cartItem">

        <button id="productButtonOne" class="cartItems">Add to cart</button>
        <img src="monaLisa.jpg" id="monaLisaImage">
        <h2 class="productDescriptions">Mona Lisa</h2>
        <p>This painting is great.</p>
        <span class=price>This item costs $10.</span>

        </div>




farGola
  • 11
  • 2
  • the code looks fine to me and i dont find any error – sayalok Oct 17 '19 at 11:40
  • 1
    Was the DOM ready before you added the listener? – Ayush Gupta Oct 17 '19 at 11:41
  • 2
    assuming the script in the bottom of the page is the one having his js code then the dom should be ready. – user254694 Oct 17 '19 at 11:42
  • The browser will parse the code from the top of the page down. If your JavaScript comes before the HTML, then the parser won't be able to find the HTML element. – Scott Marcus Oct 17 '19 at 11:44
  • Assuming the script is in `Script.js`, it is loaded correctly (at the end of the ``). The ID is correct ("loginButton"). There is no reason why this piece of code would produce an error. Do you have any other code or is this your whole application so far? – Jeremy Thille Oct 17 '19 at 12:09
  • As an aside, are you aware that Javascript code is public, and anybody can see it in their browser's developer tools, therefore everybody knows that the correct password is "123" ? – Jeremy Thille Oct 17 '19 at 12:10
  • Thanks so much for your answers and for pointing out that JavaScript code is public (this is an assignment to test that we can use the code to check for a correct pattern, but I’ll definitely keep that in mind for real-world situations). I have edited my question and posted more code above. – farGola Oct 17 '19 at 15:37

2 Answers2

-1

Place the scirpt tag after body it will work

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <title>Document</title>
</head>

<body>
    <div class=wrap>
    <input type="text" id="inputUsername">
    <p>Username</p>
    <input type="password" id="inputPswrd">
    <p>Password</p>
    <button id="loginButton">Log in</button>
    <p id="login"></p>
    </div>
    <script type="text/javascript" src="Script.js" async></script>
</body>

<script>
document.getElementById("loginButton").addEventListener("click", checkValidity);

function checkValidity() {
    var usrName = document.getElementById("inputUsername").value;
    var usrPswd = document.getElementById("inputPswrd").value;
     if(usrName == "admin" && usrPswd == "123"){
         window.open("HtmlPage2.html");
     }
     else {
         alert("Your username and password are incorrect.");
        }
    }
</script>
</html>
  • That's already what they did. `` is just before the closing body tag. Duplicating the whole script and pasting it in the HTML file a second time won't solve the problem. Downvoted. – Jeremy Thille Oct 17 '19 at 12:05
  • @JeremyThille If you look closely the post of the user the script tag is inside the body tag. But my solution is to place after closing of body tag – Rohit Sharma Oct 21 '19 at 07:07
  • 1. I don't think it will change anything. 2. You didn't move the script inclusion tag after the body tag, you wrote a new ` – Jeremy Thille Oct 21 '19 at 09:31
-2

remove this line <script type="text/javascript" src="Script.js" async></script>, I think your code loads the wrong script.

theogu
  • 13
  • 3
  • What's the correct script then? And how will removing this line solve the problem and make the whole thing work? – Jeremy Thille Oct 17 '19 at 12:06
  • Thanks for the suggestion, but I checked several times removing and replacing the path or the relative path to my script and it didn't help. – farGola Oct 17 '19 at 15:44
  • can you send back your code because it's strange it works for me – theogu Oct 18 '19 at 20:32