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

use*_*331 804 javascript dom input

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

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
Run Code Online (Sandbox Code Playgroud)

这是我的JavaScript代码:

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

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

bug*_*s94 1668

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

方法1:

document.getElementById('textbox_id').value 获得所需盒子的价值

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

 

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

方法2:

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

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

方法3:

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

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

方法4:

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

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

方法5:

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

例如, document.querySelector('#searchTxt').value;由按名称选择的标记名
document.querySelector('.searchField').value;选择的类选择的id 选择
document.querySelector('input').value;
document.querySelector('[name="searchTxt"]').value;

方法6:

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

例如, document.querySelectorAll('#searchTxt')[0].value; 由按名称 选择的标记名
document.querySelectorAll('.searchField')[0].value;选择的类选择的id 选择
document.querySelectorAll('input')[0].value;
document.querySelectorAll('[name="searchTxt"]')[0].value;

支持

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
Run Code Online (Sandbox Code Playgroud)

有用的链接

  1. 要查看这些方法的支持以及所有错误,包括更多详细信息,请单击此处
  2. 静态集合和Live集合之间的区别请单击此处
  3. NodeList和HTMLCollection之间的区别请点击这里


mau*_*lus 28

//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;
  }
}
Run Code Online (Sandbox Code Playgroud)

在codepen中看到这个功能.


小智 14

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


Vad*_*kov 14

我会创建一个变量来存储输入,如下所示:

var input = document.getElementById("input_id").value;
Run Code Online (Sandbox Code Playgroud)

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

= "Your string" + input;


Fre*_* A. 13

你应该能够输入:

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

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

我确信有更好的方法可以做到这一点,但是这个方法似乎适用于所有浏览器,并且需要对JavaScript进行最少的理解才能进行制作,改进和编辑.


Kam*_*ski 12

短的

您可以通过以下方式读取值searchTxt.value

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

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





<!-- SHORT ugly test code -->
<button class="search" onclick="searchURL()">Search</button>
Run Code Online (Sandbox Code Playgroud)


Pha*_*inh 9

如果你input在 a 中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>
Run Code Online (Sandbox Code Playgroud)

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

如果你不使用form获取价值那么

  • 您可以为每个字段设置两个不同的id(或tag或...),例如 and 、and 、...namesender-namereceiver-namesender-addressreceiver-address
  • 如果您为两个输入设置相同的值,则在getElementsByName(or getElementsByTagName...) 之后您需要记住 0 或 1 是senderor receiver。以后如果你改变了HTML中2的顺序form,就需要再次检查这段代码

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


Dhr*_*val 8

当您有多个输入字段时,可以使用onkeyup 。假设您有四个或输入。然后 document.getElementById('something').value就是烦人了。我们需要编写四行来获取输入字段的值。

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

例子:

<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>
Run Code Online (Sandbox Code Playgroud)

JavaScript:

<script>
    const data = { };

    function handleInput(e){
        data[e.name] = e.value;
    }

    function submitData(){
        console.log(data.fname); // Get the first name from the object
        console.log(data); // return object
    }
</script>
Run Code Online (Sandbox Code Playgroud)


Har*_*Das 6

试试这个

<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>
Run Code Online (Sandbox Code Playgroud)


GKi*_*lin 6

在 Chrome 和 Firefox 中测试:

通过元素id获取值:

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

在表单元素中设置值:

<form name="calc" id="calculator">
  <input type="text" name="input">
  <input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/tuq79821/

另请查看JavaScript 计算器实现

来自@bugwheels94:使用此方法时,请注意这个问题


小智 5

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