Mehul Chachada
Mehul Chachada

Reputation: 583

JavaScript error cannot get input from <input> tag

I am learner to Java Script and was trying to run this code where user enter any value in input text and then the inputted data gets print in "p" tag but when i used debugger to see where the code went wrong it pops me out with the following error

Uncaught TypeError: Cannot read property 'value' of undefined

Code:

 <!DOCTYPE html>
     <html>
     <head>
    <script>
     function myFunction() 
     {
       var a = document.getElementById("txt_1")[0].value;
       document.getElementById("demo").innerHTML = a;
     }
    </script>
    </head>
    <body>
    <form>
    <input type="text" id="txt_1" name="txt_1">
    <input type="button" onclick="myFunction()" value="Click me">
    </form>
    <p id="demo"></p>
    </body>
    </html>

Upvotes: 1

Views: 557

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68655

The getElementById() will return a single element. So you don't need to indexing [0]. Remove the [0] from the getElementById("txt_1")[0].

 <html>
     <head>
    <script>
     function myFunction() 
     {
       var a = document.getElementById("txt_1").value;
       document.getElementById("demo").innerHTML = a;
     }
    </script>
    </head>
    <body>
    <form>
    <input type="text" id="txt_1" name="txt_1">
    <input type="button" onclick="myFunction()" value="Click me">
    </form>
    <p id="demo"></p>
    </body>
    </html>

Upvotes: 4

baao
baao

Reputation: 73241

document.getElementById() returns a single element. No need to (you can't) select the first element ([0]), there will be only one.

var a = document.getElementById("txt_1").value;

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

The function document.getElementById("txt_1") returns the element, not an array that has the element as the first item, so remove the [0]:

var a = document.getElementById("txt_1").value;

Upvotes: 0

Related Questions