Error with .onclick

document.getElementById("myButton").onclick = function(){

    var myName = document.getElementById("myText").value; 


I copied exactly what the dude said in a tutorial and I got a different outcome which is an error.

Can you please also show us the HTML code that you are using? I think that we’ll find the issue in there.

<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script Src="index.js">
    <head>Enter your Name</head>
    <label>Enter your name</label><br>
    <input type="text" id="myText"><br>
    <button type="button" id="myButton">Submit</button>

Thank you. The script is above the rest of the HTML code. The script immediately runs, and none of the page below the script exists yet, so the script has nothing in the HTML code that it can find.

The solution to that which we’ve been doing for a decade or so now is to move basically all of the script tags down to the end of the body, just before the closing body tag.

Can you please let us know which tutorial is that?


There are red squiggly lines now. did I do it wrong?

and the youtube channel:

The head, label, input, and button should all be above the script tag, not inside of it.

Thank you for the video link. You can see how the HTML code should look, with the script tag below the other HTML tags, at in the video.

I understand, I guess he didn’t make it explicit, so I didn’t catch that or I might’ve not payed attention. I will try my best next time, so I don’t waste space in this forum.

Thank you

1 Like

We’re glad that you came, because something has been learned today. So far as scripts are concerned, nothing below them exists when that script is run.

There are some solutions to that, but there’s no need yet for those kind of the nitty-gritty details.

Thanks again :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.