Javascript 使用javascript检索文本字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5074059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
retrieving text field value using javascript
提问by Sanket Raut
I want to retrieve textfield value using javascript. suppose i have a code like:
我想使用 javascript 检索文本字段值。假设我有一个类似的代码:
<input type='text' name='txt'>
And I want to retrieve it using javascript. I call a function when a button is clicked:
我想使用 javascript 检索它。单击按钮时调用函数:
<input type='button' onclick='retrieve(txt)'>
What coding will the retrieve function consist of?
检索功能将包含哪些编码?
回答by Andrew Hare
You can do this:
你可以这样做:
Markup:
标记:
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="retrieve('txt');"/>
JavaScript:
JavaScript:
function retrieve(id) {
var txtbox = document.getElementById(id);
var value = txtbox.value;
}
回答by wsanville
Let's say you have an input on your page with an id of input1
, like this:
假设您的页面上有一个 ID 为 的输入input1
,如下所示:
<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:
您首先需要获取元素,如果您知道 Id,则可以使用document.getElementById('input1')
. 然后,只需调用.value
即可获取输入框的值:
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:
根据您的标记,我建议id
为您的文本框指定一个。如果您无法控制标记,您可以使用document.getElementsByName,如下所示:
var value = document.getElementsByName('txt')[0].value;
回答by sgokhales
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()
功能为 retrieve()
function retrieve()
{
var text = document.simpleForm.myText.value;
alert(text);
}