Mehul Chachada Mehul Chachada - 3 months ago 9
HTML Question

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>




Answer

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>