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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:32:08  来源:igfitidea点击:

retrieving text field value using javascript

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 .valueto 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 idfor 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);
}