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

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

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

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

如何将文本字段中的值转换为javascript?


最佳答案:

有多种方法可以直接获取输入文本框值(不将输入元素包装在表单元素中):
方法1:
document.getElementById('textbox_id').value获取
所需的框
例如,document.getElementById("searchTxt").value;
γ
注意:方法2、3、4和6返回元素集合,因此使用[整数]获得所需的出现次数。对于第一个元素,使用[0],
第二次使用,依此类推…
方法2:
使用
document.getElementsByClassName('class_name')[whole_number].value返回实时htmlcollection
例如,document.getElementsByClassName("searchField")[0].value;if this is the first textbox in your page.
方法3:
使用document.getElementsByTagName('tag_name')[whole_number].value它还返回实时htmlcollection
例如,document.getElementsByTagName("input")[0].value;,如果这是页面中的第一个文本框。
方法4:
document.getElementsByName('name')[whole_number].valuewhich also>返回活动节点列表
例如,document.getElementsByName("searchTxt")[0].value;if this is the first textbox with name'searchtext'in your page.
方法5:
使用功能强大的document.querySelector('selector').value来选择元素
例如,document.querySelector('#searchTxt').value;selected by id
document.querySelector('.searchField').value;按类选择
document.querySelector('input').value;由标记名选择
document.querySelector('[name="searchTxt"]').value;按名称选择
方法6:
document.querySelectorAll('selector')[whole_number].value它还使用CSS选择器来选择元素,但它将使用该选择器的所有元素作为静态节点列表返回。
例如,document.querySelectorAll('#searchTxt')[0].value;selected by id
document.querySelectorAll('.searchField')[0].value;按类选择
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

有用的链接
1
To see the support of these methods with all the bugs including more details click here
Difference Between Static collections and Live collections click Here