Anjan Dutta
How to get the value of text input field using JavaScript
How to get the value of text input field using JavaScript
In javascript, we can get the value of a text input field by accessing the input field using its
id
in javascript.
First, we need to define the input element inside containing form tags like below.
<form id="myForm" name="myform" onsubmit="return false;"> <label for="u_name">Enter your name</label> <input type="text" id="u_name_id" name="u_name"/> <button name="button" onclick="getValue()">Get Value</button></form>
Then, in our javascript code, we can access the input field's value like this.
var nameValue = document.getElementById("u_name_id").value
Here is the complete example.
HTML Code
<html> <head> <title>Accessing form value</title> </head> <body> <form id="myForm" name="myform" onsubmit="return false;"> <label for="u_name">Enter your name</label> <input type="text" id="u_name_id" name="u_name"/> <button name="button" onclick="getValue()">Get Value</button> </form> <div id="display"> </div> </body></html>
Javascript Code
function getValue() { var nameValue = document.getElementById("u_name_id").value; /*Displaying the acquired value*/
document.getElementById("display").innerHTML = "Hello, " + nameValue;}