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


当前回答

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

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

来源:w3schools

其他回答

简短的回答

你可以使用下面的代码使用JavaScript获取文本输入字段的值:

更多信息

textObject有一个value属性,你可以设置和获取这个属性。

要设置,您可以指定一个新值: . getelementbyid(“searchTxt”)。Value = "新值"

在Chrome和Firefox中测试:

通过元素id获取值:

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

在form元素中设置值:

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

还有一个JavaScript计算器实现。

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

//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;
  }
}

请在代码依赖中查看此功能。

你可以通过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有最少的了解就可以进行制作、改进和编辑。