skip to Main Content

When I’m taking value from input field ‘username’ through querySelector or getElementById it shows that it is null.

The error is: cannot read properties of null (reading ‘value’)

This is the HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style_index.css">
    <title>Home</title>
</head>
<body>
    <!--Logo-->
    <div class="logo">
        <img src="./images/logo1.png" alt="" class="logoimg">
    </div>

    <div class="content">
        <div class="container1">
            <h1>Join Lobby</h1>

                <label>Username</label><br>
                <input type="text" id="username"/><br>
                <label>Lobby Password</label><br>
                <input type="password" id="pswd"/><br>
                <a href="./GamingArena.html"><button type="submit" onclick="join()" class="join">Join</button></a>
         
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.6.1/socket.io.js"></script>
    <script type="javascript" src="./index.js"></script>
    <script src="./script.js"></script>
</body>
</html>

This is the script.js file

    const app = document.querySelector(".app");
    const socket = io();

    let uname;
    function join(){
        let username = app.querySelector(".content .container1 #username").value;
        if(username.length == 0){
            return;
        }

        socket.emit("newuser", username);
        uname = username;
        console.log(username);
    };

I was expecting to store value from the input field ‘username’ in the variable username.

2

Answers


  1. In the first line of the script you are creating the const "app", which looks for an element with the "app" class, which is not present in the html

    Simply add the missing class to any wrapping element. or instead of using the app constant use the document.

    Login or Signup to reply.
  2. you can move your script tag to the bottom of the HTML body, just before the closing tag. This will ensure that the HTML has fully loaded before your JavaScript runs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search