我正在用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?


当前回答

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

其他回答

我们可以使用这种形式。元素来获取表单中的所有元素。如果一个元素有id,它可以用. nameditem ("id")找到。例子:

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

来源:w3schools

你可以通过searchTxt.value读取值

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/> < script type = " text / javascript " > 函数searchURL () { console.log (searchTxt.value); / /窗口。location = "http://www.myurl.com/search/" + searchTxt.value; } > < /脚本 <!——短小丑陋的测试代码——> <button class="search" onclick="searchURL()“>搜索> < /按钮

你应该能够输入:

var input = document.getElementById(“searchTxt”); 函数搜索URL() { window.location = “http://www.myurl.com/search/” + input.value; } <input name=“searchTxt” type=“text” maxlength=“512” id=“searchTxt” class=“searchField”/>

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

你也可以,通过标签名称调用,像这样: 所以你会得到特定形式的特定输入值。

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