Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My button in html not responding to my js

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

`<!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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading