So i am learning javascript and i am checking out js reactiong to my html button and this does not seem to work it always says "cannot read properties of undefined(reading ‘log’)"
Here’s my code:
Html:
`<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<label>name: </label>
<input type= text id ="mytext">
<button type=button id= "mybutton"> submit</button>
<body>
<script src = index.js></script>
</body>
</html>`
Js:
let name = undefined;
document.getElementById("mybutton").onclick = function(){
let name = document.getElementById("mytext")
}
console.log(name);
>Solution :
There are a few issues with the code you provided. First, the script tag should be inside the head or body tag. Second, the code that assigns the value of the text input to the name variable should be inside the click event handler function.
document.getElementById("mybutton").onclick = function() {
let name = document.getElementById("mytext").value;
console.log(name);
}
<html>
<head>
<title></title>
</head>
<body>
<label>name: </label>
<input type="text" id="mytext">
<button type="button" id="mybutton">submit</button>
<script src="index.js"></script>
</body>
</html>