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


当前回答

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

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

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

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

其他回答

当你有多个输入字段时,你可以使用onkeyup。假设你有四个输入。然后 . getelementbyid(“什么”)。价值是恼人的。我们需要写四行来获取输入字段的值。

因此,你可以创建一个函数,在keyup或keydown事件时将值存储在object中。

例子:

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

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>

你可以通过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()“>搜索> < /按钮

//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 = "新值"

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