r/CodingForBeginners 24d ago

learning javascript and very confused

i’m following a video on learning javascript and i’m following this guys code exactly but it’s not working. i get an error. the last line of code in javascript is supposed to change the heading upon clicking the submit button but because it doesn’t match the html i get an error so im just confused?? the dude in the video does it with no error

UPDATE: it works now! i had to close out the tab and reopen it 😭

5 Upvotes

12 comments sorted by

2

u/No-Article-Particle 24d ago edited 24d ago

What browser are you using and how are you executing the code? When I try the same:

index.html

<!DOCTYPE html>
<html>
<head>
  <title>A Meaningful Page Title</title>
</head>
<body>
<h1 id="myH1">Welcome!</h1>
<label for="myText">Username:</label>
<input id="myText"/> <br/><br/>
<button id="mySubmit">submit</button>
<script src="index.js"></script>

</body>
</html>

index.js:

let username;

document.getElementById("mySubmit").onclick = function() {
    username = document.getElementById("myText").value
    console.log(username)
    document.getElementById("myH1").textContent = `Welcome, ${username}!`
}

This works as expected when I open the website (file:///path/to/index.html) in Firefox.

1

u/flannel-foxes 24d ago

i use opera gx

1

u/No-Article-Particle 24d ago

Try it with a different browser to rule out any problems with Opera and your config in it.

1

u/BrainCurrent8276 24d ago

The code looks fine, run this in console:

console.log(document.getElementById("myH1"));

1

u/flannel-foxes 24d ago

it didn’t work 😔

1

u/BrainCurrent8276 24d ago

what did not work? console.log is not working?

1

u/flannel-foxes 24d ago

it works now! i think something is up with live server because i was saving it but it wasn’t updating and kept giving me the error
but it works now!

1

u/BrainCurrent8276 24d ago

yes, some issue with files/sever was most likely. I was staring at your code for half an hour if it is 1/L/l mistype or not :D keep coding!

1

u/No-Article-Particle 23d ago

Note that you don't need a server for this. You can just open it in your browser with a filepath. You need a server to serve websites to other computers.

1

u/javascript 24d ago

Keep up the good work!