5

I want to retrieve textfield value using javascript. suppose i have a code like:

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

And I want to retrieve it using javascript. I call a function when a button is clicked:

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

What coding will the retrieve function consist of?

3 Answers 3

12

You can do this:

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also change name='txt' to id='txt' (or add it) on the text input.
2

Let's say you have an input on your page with an id of input1, like this:

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

You first need to get the element, and if you know the Id, you can use document.getElementById('input1'). Then, just call .value to get the value of the input box:

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

Update

Based on your markup, I would suggest specifying an id for your text box. Incase you don't have control over the markup, you can use document.getElementsByName, like so:

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

Comments

0

One of the way is already explained by Andrew Hare.

You can also do it by entering the value in the textbox and getting a prompt box with entered message when a user click the button.

Let's say, you have a textbox and a input button

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

The function for retrieve()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.