Another article on Javascript client-side scripting which is mainly focus on how to get value of an input type field in javascript. Basically, there is a form which has at least one input type field and one submit button. Based on that HTML element, in this article through its writing, retrieving the value inserted in an input type HTML element. The value will be retrieved through a clicked event of a submit button.
The following are the source code for defining a form used to get the value from :
<html> <head> <title>Javascript : Getting value from an input type field</title> </head> <body> <form id="myform"> <input type="text" id="input_text"></input type> <input type="submit" onClick="getValue()"></input> </form> </body> </html>
The important thing from the above input type text field is the identifier itself. It is defined in an attribute of the input type HTML element named ‘id’. The value of the attribute in the above ‘id’ attribute is ‘input_text’. Another important thing is the attribute onClick defined in the input type submit button HTML element. By clicking this submit button, it will then call a Javascript method named ‘getValue()’.
The javascript snippet code which is used to retrieve the value from the text field defined inside a form is shown below :
<script type="text/javascript"> function getValue() { var text = document.getElementById("input_text").value; alert("Name : "+text); } </script>
The javascript snippet code above has an important role for retrieving the value inserted in the input type text field HTML element presented before. It is actually triggered by an onClick attribute defined in the submit button type HTML element. By clicking the submit button, it will eventually call a method named ‘getValue()’. By the time the method is called and being processed, it will then get the value which is inserted in the input type text field HTML element with the id of ‘input_text’. In the end, it will be displayed in a pop-up window which is represented by the line of code ‘alert(“Name : “+text);
Just place it inside the ‘<head></head>’ HTML element section, so the snippet code overall will be shown below :
<html> <head> <title>Javascript : Getting value from an input type field</title> <script type="text/javascript"> function getValue() { var name = document.getElementById("name").value; alert("Name : "+name); } </script> </head> <body> <form id="myform"> <input type="text" id="name"> </input type> <input type="submit" onClick="getValue()"> </input> </form> </body> </html>
One thought on “How to get Value of Input Type Field in Javascript”