简体   繁体   English

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

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

I am working on a search with JavaScript.我正在使用 JavaScript 进行搜索。 I would use a form, but it messes up something else on my page.我会使用一个表单,但它会弄乱我页面上的其他内容。 I have this input text field:我有这个输入文本字段:

<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 中?

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').value to get the value of desired box document.getElementById('textbox_id').value获取所需框的值

For example, document.getElementById("searchTxt").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.注意:方法 2,3,4 和 6 返回元素的集合,因此使用 [whole_number] 来获取所需的出现次数。 For the first element, use [0], for the second one use 1 , and so on...对于第一个元素,使用 [0],对于第二个元素,使用1 ,依此类推...

Method 2:方法二:

Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection使用document.getElementsByClassName('class_name')[whole_number].value返回一个 Live HTMLCollection

For example, document.getElementsByClassName("searchField")[0].value;例如document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.如果这是您页面中的第一个文本框。

Method 3:方法三:

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection使用document.getElementsByTagName('tag_name')[whole_number].value它还返回一个实时 HTMLCollection

For example, document.getElementsByTagName("input")[0].value;例如document.getElementsByTagName("input")[0].value; , if this is the first textbox in your page. ,如果这是您页面中的第一个文本框。

Method 4:方法四:

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList document.getElementsByName('name')[whole_number].value也 > 返回一个活动的 NodeList

For example, document.getElementsByName("searchTxt")[0].value;例如document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.如果这是您页面中第一个名称为“searchtext”的文本框。

Method 5:方法五:

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element使用强大的document.querySelector('selector').value ,它使用 CSS 选择器来选择元素

For example, document.querySelector('#searchTxt').value;例如document.querySelector('#searchTxt').value; selected by id由 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].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist. document.querySelectorAll('selector')[whole_number].value也使用 CSS 选择器来选择元素,但它会将具有该选择器的所有元素作为静态节点列表返回。

For example, document.querySelectorAll('#searchTxt')[0].value;例如document.querySelectorAll('#searchTxt')[0].value; selected by id由 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 NodeList 和 HTMLCollection 的区别点击这里
//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 中查看此功能。

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;

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 的最少了解来制作、改进和编辑。

Also you can, call by tags names, like this: form_name.input_name.value;您也可以通过标签名称调用,如下所示: form_name.input_name.value; So you will have the specific value of determined input in a specific form.因此,您将具有特定形式的确定输入的特定值。

<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>

Short短的

You can read value by searchTxt.value您可以通过searchTxt.value读取值

 function searchURL() { let txt = searchTxt.value; console.log(txt); // window.location = "http://www.myurl.com/search/" + txt; ... } document.querySelector('.search').addEventListener("click", ()=>searchURL());
 <input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/> <button class="search">Search</button>

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 的更新:使用此方法时请注意此问题

You can use onkeyup when you have more input field.当您有更多输入字段时,您可以使用 onkeyup。 Suppose you have four or input.then document.getElementById('something').value is annoying.假设你有四个或 input.then document.getElementById('something').value很烦人。 we need to write 4 lines to fetch value of input field.我们需要写 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>

If your input is in a form and you want to get value after submit you can do like如果您的input是在form中并且您希望在提交后获得价值,您可以这样做

<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 2 form for input sender and receiver information.这种方式的好处:例如,您的页面有2 个form用于输入senderreceiver信息。

If you don't use form for get value then如果您不使用form获取价值,那么
- You can set 2 different id (or tag or name ...) for each field like sender-name and receiver-name , sender-address and receiver-address , ... - 您可以为每个字段设置 2 个不同的id (或tagname ...),例如sender-namereceiver-namesender-addressreceiver-address ,...
- If you set same value for 2 input, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver . - 如果您为 2 个输入设置相同的值,那么在getElementsByName (或getElementsByTagName ...)之后,您需要记住 0 或 1 是senderreceiver Later if you change the order of 2 form in html, you need to check this code again后面如果在html中改变了2个form的顺序,需要再次查看这段代码

If you use form , then you can use name , address , ...如果你使用form ,那么你可以使用name , address , ...

 function handleValueChange() { var y = document.getElementById('textbox_id').value; var x = document.getElementById('result'); x.innerHTML = y; } function changeTextarea() { var a = document.getElementById('text-area').value; var b = document.getElementById('text-area-result'); b.innerHTML = a; }
 input { padding: 5px; } p { white-space: pre; }
 <input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()"> <p id="result"></p> <textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea> <p id="text-area-result"></p>

<input id="new" >
    <button  onselect="myFunction()">it</button>    
    <script>
        function myFunction() {
            document.getElementById("new").value = "a";    
        }
    </script>

One can use the form.elements to get all elements in a form.可以使用 form.elements 获取表单中的所有元素。 If an element has id it can be found with .namedItem("id").如果一个元素有 id,它可以通过 .namedItem("id") 找到。 Example:例子:

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

Source: w3schools资料来源: w3schools

simple js简单的js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}
function searchURL() {
   window.location = 'http://www.myurl.com/search/' + searchTxt.value
}

So basically searchTxt.value will return the value of the input field with id='searchTxt' .所以基本上searchTxt.value将返回id='searchTxt'的输入字段的值。

Short Answer简答

You can get the value of text input field using JavaScript with this code: input_text_value = console.log(document.getElementById("searchTxt").value)您可以通过以下代码使用 JavaScript 获取文本输入字段的值: input_text_value = console.log(document.getElementById("searchTxt").value)

More info更多信息

textObject has a property of value you can set and get this property. textObject有一个value属性,您可以设置和获取此属性。

To set you can assign a new value: document.getElementById("searchTxt").value = "new value"要进行设置,您可以分配一个新值: document.getElementById("searchTxt").value = "new value"

If you are using jQuery then by using plugin formInteract, you just need to do this:如果您使用的是 jQuery,那么通过使用插件 formInteract,您只需要这样做:

// Just keep the HTML as it is.

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

At bottom of the page just include this plugin file and write this code:在页面底部只包含此插件文件并编写以下代码:

// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();

search.getAjax("http://www.myurl.com/search/", function(rsp){
    // Now do whatever you want to with your response
});

Or if using a parameterized URL then use this:或者,如果使用参数化 URL,则使用以下命令:

$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
    // Now do work with your response;
})

Here is the link to project https://bitbucket.org/ranjeet1985/forminteract这是项目的链接https://bitbucket.org/ranjeet1985/forminteract

You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more.您可以将此插件用于多种用途,例如获取表单的值、将值放入表单、验证表单等等。 You can see some example of code in the index.html file of the project.您可以在项目的 index.html 文件中看到一些代码示例。

Of course I am the author of this project and all are welcome to make it better.当然我是这个项目的作者,欢迎大家把它做得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM