skip to Main Content

I am trying to do the simple task of copying the value of the first text boxbox to the second textbox

here is my html

<html>
    <head>
         <link rel="stylesheet" href="Style.css">   
         <script src="1.js"></script>
    </head>
    <body>
        textbox1: <input id="textbox1" onkeyup="TextCopy()" type="text"> <br>
        textbox2: <input id="textbox2"  type="text">
    </body>
</html>

here is my js file:

const text1 = document.getElementById("textbox1");
const text2 = document.getElementById("textbox2");

function TextCopy() {

    text2.value = text1.value;
}

the error i get is:
1.js:6 Uncaught TypeError: Cannot read properties of null (reading ‘value’)
at TextCopy (1.js:6:25)
at HTMLInputElement.onkeyup (1.html:7:73)

if I declare text1 and text2 inside the function I get no errors and it works correctly, so why doesn’t it work when I declare them as global variables?

thanks.

3

Answers


  1. Your elements don’t exist at the time your script is run. That is why people put their script files at the end of the body, and not in the head. You can also use the defer attribute.
    <script src="script.js" defer></script>

    Login or Signup to reply.
  2. You fetch your elements faster than HTML has them rendered, that’s why JS can’t find them in DOM. Move script to the end of body or wrap it in DOM Ready event:

    <html>
        <head>
             <link rel="stylesheet" href="Style.css">   
        </head>
        <body>
            textbox1: <input id="textbox1" onkeyup="TextCopy()" type="text"> <br>
            textbox2: <input id="textbox2"  type="text">
    
             <script src="1.js"></script>
        </body>
    </html>
    
    
    window.addEventListener("DOMContentLoaded", (event) => {
        const text1 = document.getElementById("textbox1");
        const text2 = document.getElementById("textbox2");
        
        function TextCopy() {
            text2.value = text1.value;
        }
    });
    
    Login or Signup to reply.
  3. Your sript executes before the page has the time to fully load, in order to force javascript to wait for the DOM to be loaded completely you must use the defer keyword in your script tag

    <html>
    <head>
         <link rel="stylesheet" href="Style.css">   
         <script src="1.js" defer></script>
    </head>
    <body>
        textbox1: <input id="textbox1" onkeyup="TextCopy()" type="text"> <br>
        textbox2: <input id="textbox2"  type="text">
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search