skip to Main Content

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);

3

Answers


  1. The solution is sth like that:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Input Field Example</title>
      </head>
      <body>
        <input type="text" id="input-field">
        <button onclick="logInput()">Log Input</button>
        <script>
          function logInput() {
            const input = document.getElementById("input-field").value;
            console.log(input);
          }
        </script>
      </body>
    </html>
    

    Your code has two simple bugs, or wrong usages.

    1. you need to add .value after document.getElementById("mytext")
    2. Not console.console.log(name) but console.log(name)
    Login or Signup to reply.
  2. <html>
    <head>
      <title>Test Javascript</title>
    </head>
    <body>
    <label>name: </label>
    <input type="text" id ="mytext">
    <button type="button" id= "mybutton"> submit</button>
    
    
    <!-- <script src = index.js></script> -->
    
    
    <script>//here i am using internal script you may use your script in your way 
    document.getElementById("mybutton").onclick = function(){
        let name = document.getElementById("mytext").value;
    console.log(name);
    }
    </script>
    </body>
    </html>
    
    Login or Signup to reply.
  3. here is an example:
    html code:

    <div id="myelement">
    <button type="button" id="mybutton">Show Text</button>
    <input type="text" id="mytext"></input>
    </div>
    

    javascript code:

    document.getElementById("mybutton").onclick = function(){
    
        text = document.getElementById("mytext").value;
    
      console.log(text); 
     
    }
    

    use call the console log inside the function. also you have duplicated console console.console.log(name); you should use console.log(name);

    here is the jsfiddle test : https://jsfiddle.net/qxucho84/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search