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


当前回答

如果你的输入是一个表单,你想在提交后得到值,你可以这样做:

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

这样做的好处:例如你的页面有2个表单用于输入发送方和接收方信息。

如果你不使用形式来获取价值

你可以为每个字段设置两个不同的id(或标签或名称…),比如sender-name和receiver-name, sender-address和receiver-address,… 如果为两个输入设置相同的值,那么在getElementsByName(或getElementsByTagName…)之后,您需要记住0或1是发送方或接收方。稍后,如果您更改HTML中2表单的顺序,则需要再次检查此代码

如果你用form,那么你可以用name, address,…

其他回答

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

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

简短的回答

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

更多信息

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

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

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

我将创建一个变量来存储输入,就像这样:

var input = document.getElementById("input_id").value;

然后我用变量把输入值加到字符串中。

=“你的字符串”+输入;