How do I get the value of text input field using J

2018-12-31 00:09发布

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:

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

And this is my JavaScript code:

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

How do I get the value from the text field into JavaScript?

11条回答
柔情千种
2楼-- · 2018-12-31 00:39

I would create a variable to store the input like this:

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

And then I would just use the variable to add the input value to the string.

= "Your string" + input;

查看更多
零度萤火
3楼-- · 2018-12-31 00:41

You should be able to type:

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

<script>
    var input = document.getElementById("searchTxt");

    function searchURL() {
         window.location = "http://www.myurl.com/search/" + input.value;
    }
</script>

I'm sure there are better ways to do this, but this one seems to work across all browsers, and it requires minimal understanding of JavaScript to make, improve, and edit.

查看更多
只若初见
4楼-- · 2018-12-31 00:43

Try this one

<input type="text" onKeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value)
{

window.open("http://www.google.co.in/search?output=search&q="+value)

}
</script>
查看更多
查无此人
5楼-- · 2018-12-31 00:51
//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;
  }
}

See this functioning in codepen.

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 00:51

Tested in Chrome and Firefox:

Get value by element id:

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

Set value in form element:

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

Also have a look at a JavaScript calculator implementation: http://www.4stud.info/web-programming/samples/dhtml-calculator.html

UPDATE from @bugwheels94: when using this method be aware of this issue.

查看更多
浮光初槿花落
7楼-- · 2018-12-31 00:52

Also you can, call by tags names, like this: form_name.input_name.value; So you will have the specific value of determined input in a specific form.

查看更多
登录 后发表回答