01 January 2014

How to get Input Text value using Javascript

javascript
In website development,we may need to work with the text that is entered in the input. It can be get using javascript withint the html. Check the following code:



Code 1:
<input type="text" id="username" name="username">
<input type="button" onclick=(run()); value="Show">
<script>
function run()
{
var pa = document.getElementById("username");
alert( pa.value );
}
</script>

Explaination:

  • document.getElementById("") returns the tag with that id
  • pa is a variable which holds the tag object
  • pa.value returns the value of the tag object.
  • alert()  shows messege box(used to check if it returns the correct input value for debug)
  • onclick() is a function which is called when the button is clicked
  • run() is a user made custom fuction


Another way: Code 2
<form name="login">
<input type="text" id="username" name="username">
<input type="button" onclick=(run()); value="show">
</form>
<script>
function run()
{
var pa = login.username ;
alert( pa.value );
}
</script>


Explaination:


  • login is the form object name that can be used directly. You can name the Form tag with any name.
  • login.username is the input text object that is inside that form tag
  • login.username.value can also be used directly without storing into the variable.



(If you found this article useful then share with your friends.)

No comments: