如何使用 JavaScript 获取文本输入字段的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11563638/
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-24 06:20:36  来源:igfitidea点击:

How do I get the value of text input field using JavaScript?

javascriptdomhtml-input

提问by user979331

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:

我正在使用 JavaScript 进行搜索。我会使用表单,但它会弄乱我页面上的其他内容。我有这个输入文本字段:

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

And this is my JavaScript code:

这是我的 JavaScript 代码:

<script type="text/javascript">
  function searchURL(){
    window.location = "http://www.myurl.com/search/" + (input text value);
  }
</script>

How do I get the value from the text field into JavaScript?

如何将文本字段中的值获取到 JavaScript 中?

回答by bugwheels94

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

有多种方法可以直接获取输入文本框值(无需将输入元素包装在表单元素中):

Method 1:

方法一:

document.getElementById('textbox_id').valueto get the value of desired box

For example,document.getElementById("searchTxt").value;

document.getElementById('textbox_id').value获取所需框的值

例如,document.getElementById("searchTxt").value;

 

 

Note:Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...

注意:方法 2、3、4 和 6 返回元素的集合,因此使用 [whole_number] 来获取所需的出现次数。对于第一个元素,使用 [0],对于第二个元素,使用1,依此类推...

Method 2:

方法二:

Use document.getElementsByClassName('class_name')[whole_number].valuewhich returns a Live HTMLCollection

For example,document.getElementsByClassName("searchField")[0].value;if this is the first textbox in your page.

使用 document.getElementsByClassName('class_name')[whole_number].value它返回一个 Live HTMLCollection

例如,document.getElementsByClassName("searchField")[0].value;如果这是您页面中的第一个文本框。

Method 3:

方法三:

Use document.getElementsByTagName('tag_name')[whole_number].valuewhich also returns a live HTMLCollection

For example,document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

使用document.getElementsByTagName('tag_name')[whole_number].value它也返回一个实时的 HTMLCollection

例如,document.getElementsByTagName("input")[0].value;如果这是您页面中的第一个文本框。

Method 4:

方法四:

document.getElementsByName('name')[whole_number].valuewhich also >returns a live NodeList

For example,document.getElementsByName("searchTxt")[0].value;if this is the first textbox with name 'searchtext' in your page.

document.getElementsByName('name')[whole_number].value这也 > 返回一个实时 NodeList

例如,document.getElementsByName("searchTxt")[0].value;如果这是您页面中第一个名为“searchtext”的文本框。

Method 5:

方法五:

Use the powerful document.querySelector('selector').valuewhich uses a CSS selector to select the element

For example,document.querySelector('#searchTxt').value;selected by id
document.querySelector('.searchField').value;selected by class
document.querySelector('input').value;selected by tagname
document.querySelector('[name="searchTxt"]').value;selected by name

使用强大document.querySelector('selector').value的 CSS 选择器来选择元素

比如document.querySelector('#searchTxt').value;select by id
document.querySelector('.searchField').value;selected by class
document.querySelector('input').value;selected by tagname
document.querySelector('[name="searchTxt"]').value;selected by name

Method 6:

方法六:

document.querySelectorAll('selector')[whole_number].valuewhich also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example,document.querySelectorAll('#searchTxt')[0].value;selected by id
document.querySelectorAll('.searchField')[0].value;selected by class
document.querySelectorAll('input')[0].value;selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value;selected by name

document.querySelectorAll('selector')[whole_number].value它也使用 CSS 选择器来选择元素,但它将所有具有该选择器的元素作为静态节点列表返回。

比如document.querySelectorAll('#searchTxt')[0].value;select by id
document.querySelectorAll('.searchField')[0].value;selected by class
document.querySelectorAll('input')[0].value;selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value;selected by name

Support

支持

Browser          Method1   Method2  Method3  Method4    Method5/6
IE6              Y(Buggy)   N        Y        Y(Buggy)   N
IE7              Y(Buggy)   N        Y        Y(Buggy)   N
IE8              Y          N        Y        Y(Buggy)   Y
IE9              Y          Y        Y        Y(Buggy)   Y
IE10             Y          Y        Y        Y          Y
FF3.0            Y          Y        Y        Y          N    IE=Internet Explorer
FF3.5/FF3.6      Y          Y        Y        Y          Y    FF=Mozilla Firefox
FF4b1            Y          Y        Y        Y          Y    GC=Google Chrome
GC4/GC5          Y          Y        Y        Y          Y    Y=YES,N=NO
Safari4/Safari5  Y          Y        Y        Y          Y
Opera10.10/
Opera10.53/      Y          Y        Y        Y(Buggy)   Y
Opera10.60
Opera 12         Y          Y        Y        Y          Y

Useful links

有用的链接

  1. To see the support of these methods with all the bugs including more details click here
  2. Difference Between Static collections and Live collections click Here
  3. Difference Between NodeList and HTMLCollection click Here
  1. 要查看这些方法对所有错误的支持,包括更多详细信息,请单击此处
  2. 静态集合和实时集合之间的区别单击此处
  3. NodeList 和 HTMLCollection 的区别点击这里

回答by maudulus

//creates a listener for when you press a key
window.onkeyup = keyup;

//creates a global Javascript variable
var inputTextValue;

function keyup(e) {
  //setting your input text to the global Javascript Variable for every key press
  inputTextValue = e.target.value;

  //listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
  if (e.keyCode == 13) {
    window.location = "http://www.myurl.com/search/" + inputTextValue;
  }
}

See this functioning in codepen.

在 codepen 中查看此功能。

回答by Vadim Tatarnikov

I would create a variable to store the input like this:

我会创建一个变量来存储这样的输入:

var input = document.getElementById("input_id").value;

And then I would just use the variable to add the input value to the string.

然后我将只使用变量将输入值添加到字符串中。

= "Your string" + input;

= "Your string" + input;

回答by Fredrik A.

You should be able to type:

您应该能够输入:

var input = document.getElementById("searchTxt");

function searchURL() {
     window.location = "http://www.myurl.com/search/" + input.value;
}
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

I'm sure there are better ways to do this, but this one seems to work across all browsers, and it requires minimal understanding of JavaScript to make, improve, and edit.

我相信有更好的方法可以做到这一点,但这个方法似乎适用于所有浏览器,并且它只需要对 JavaScript 的了解最少,就可以制作、改进和编辑。

回答by user3768564

Also you can, call by tags names, like this: form_name.input_name.value;So you will have the specific value of determined input in a specific form.

您也可以通过标签名称调用,如下所示:form_name.input_name.value;因此您将获得特定形式的确定输入的特定值。

回答by Hari Das

Try this one

试试这个

<input type="text" onkeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value) {
    window.open("http://www.google.com/search?output=search&q=" + value)
}
</script>

回答by Grigory Kislin

Tested in Chrome and Firefox:

在 Chrome 和 Firefox 中测试:

Get value by element id:

通过元素 id 获取值:

<input type="text" maxlength="512" id="searchTxt" class="searchField"/>
<input type="button" value="Get Value" onclick="alert(searchTxt.value)">

Set value in form element:

在表单元素中设置值:

<form name="calc" id="calculator">
  <input type="text" name="input">
  <input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>

https://jsfiddle.net/tuq79821/

https://jsfiddle.net/tuq79821/

Also have a look at a JavaScript calculator implementation: http://www.4stud.info/web-programming/samples/dhtml-calculator.html

也看看 JavaScript 计算器实现:http: //www.4stud.info/web-programming/samples/dhtml-calculator.html

UPDATE from @bugwheels94: when using this method be aware of this issue.

来自@bugwheels94 的更新:使用此方法时请注意此问题

回答by Valter Ekholm

One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:

可以使用 form.element 来获取表单中的所有元素。如果元素具有 id,则可以使用 .namedItem("id") 找到它。例子:

var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;

Source: w3schools

资料来源:w3schools

回答by Dhruv Raval

You can use onkeyup when you have more input field. Suppose you have four or input.then document.getElementById('something').valueis annoying. we need to write 4 lines to fetch value of input field.

当您有更多输入字段时,您可以使用 onkeyup。假设你有四个或 input.then document.getElementById('something').value很烦人。我们需要写 4 行来获取输入字段的值。

So, you can create a function that store value in object on keyup or keydown event.

因此,您可以创建一个函数,在 keyup 或 keydown 事件上将值存储在对象中。

Example :

例子 :

<div class="container">
    <div>
        <label for="">Name</label>
        <input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
    </div>
    <div>
        <label for="">Age</label>
        <input type="number" name="age" id="age" onkeyup=handleInput(this)>
    </div>
    <div>
        <label for="">Email</label>
        <input type="text" name="email" id="email" onkeyup=handleInput(this)>
    </div>
    <div>
        <label for="">Mobile</label>
        <input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
    </div>
    <div>
        <button onclick=submitData()>Submit</button>
    </div>
</div>

javascript :

javascript :

<script>
    const data={ };
    function handleInput(e){
        data[e.name] = e.value;
    }
    function submitData(){
        console.log(data.fname); //get first name from object
        console.log(data); //return object
    }
</script>

回答by Phan Van Linh

If your inputis in a formand you want to get value after submit you can do like

如果您input在 aform并且您想在提交后获得价值,您可以这样做

<form onsubmit="submitLoginForm(event)">
    <input type="text" name="name">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<script type="text/javascript">

    function submitLoginForm(event){
        event.preventDefault();

        console.log(event.target['name'].value);
        console.log(event.target['password'].value);
    }
</script>

Benefit of this way: Example your page have 2formfor input senderand receiverinformation.

这种方式的好处:例如您的页面有2 个form用于输入senderreceiver信息。

Ifyou don't use formfor get value then
- You can set 2 different id(or tagor name...) for each field like sender-nameand receiver-name, sender-addressand receiver-address, ...
- If you set same value for 2 input, then after getElementsByName(or getElementsByTagName...) you need to remember 0 or 1 is senderor receiver. Later if you change the order of 2 formin html, you need to check this code again

如果你不使用form的GET值,那么
-你可以设置2个不同的id(或tagname......)每个字段像sender-namereceiver-namesender-addressreceiver-address,...
-如果你2输入设定值相同,则后getElementsByName(或getElementsByTagName.. .) 你需要记住 0 or 1 is senderor receiver。以后如果form在html中改变2的顺序,需要再次检查这段代码

Ifyou use form, then you can use name, address, ...

如果您使用form,那么您可以使用name, address, ...