Getting text box value using javascript

I want to get the value of a text field using javascript. Suppose I have code like:

 <input type='text' name='txt'>

And I want to get it using javascript. I call the function when the button is clicked:

<input type='button' onclick='retrieve(txt)'>

What encoding will the extraction function perform?

+5
source share
3 answers

You can do it:

Markup:

<input type="text" name="txt" id="txt"/>
<input type="button" onclick="retrieve('txt');"/>

JavaScript:

function retrieve(id) {
    var txtbox = document.getElementById(id);
    var value = txtbox.value;
}
+12
source

Let's say you have an entry on your page with an id input1, for example:

<input type="text" id="input1" />

First you need to get the item, and if you know Id, you can use document.getElementById('input1'). Then just call .valueto get the value of the input field:

var value = document.getElementById('input1').value;

Update

, id . , document.getElementsByName, :

var value = document.getElementsByName('txt')[0].value;
+2

One way is already explained by Andrew Hare .

You can also do this by entering a value in the text box and receiving a prompt window with the message entered when the user clicks the button.

Say you have a text box and an enter button

<input type="text" name="myText" size="20" />
<input type="button" value="Alert Text" onclick="retrieve()" />  

Function for retrieve()

function retrieve()
{
     var text = document.simpleForm.myText.value;
     alert(text);
}
0
source

All Articles