1215

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user979331
  • 11,039
  • 73
  • 223
  • 418

16 Answers16

2327

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

Method 1

document.getElementById('textbox_id').value to get the value of desired box

For example

document.getElementById("searchTxt").value;

  Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use [1], and so on...

Method 2

Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example

document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.

Method 3

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example

document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

Method 4

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList

For example

document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.

Method 5

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element

For example

  • document.querySelector('#searchTxt').value; selected by id
  • document.querySelector('.searchField').value; selected by class
  • document.querySelector('input').value; selected by tagname
  • document.querySelector('[name="searchTxt"]').value; selected by name

Method 6

document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example

  • document.querySelectorAll('#searchTxt')[0].value; selected by id
  • document.querySelectorAll('.searchField')[0].value; selected by class
  • document.querySelectorAll('input')[0].value; selected by tagname
  • document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name

Support

Browser Method1 Method2 Method3 Method4 Method5/6
IE6 Y(Buggy) N Y Y(Buggy) N
IE7 Y(Buggy) N Y Y(Buggy) N
IE8 Y N Y Y(Buggy) Y
IE9 Y Y Y Y(Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N IE=Internet Explorer
FF3.5/FF3.6 Y Y Y Y Y FF=Mozilla Firefox
FF4b1 Y Y Y Y Y GC=Google Chrome
GC4/GC5 Y Y Y Y Y Y=YES,N=NO
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y(Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y

Useful links

  1. To see the support of these methods with all the bugs including more details click here
  2. Difference Between Static collections and Live collections click Here
  3. Difference Between NodeList and HTMLCollection click Here
VLAZ
  • 26,331
  • 9
  • 49
  • 67
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
  • IE8 [supports QSA](https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll#Browser_compatibility) as far as I can see, it just doesn't support CSS3 selectors in the selector string. – Fabrício Matté Jun 22 '13 at 04:02
  • @FabrícioMatté i just checked here http://www.quirksmode.org/dom/tests/basics.html#querySelectorAll and it told me that it doesnot – bugwheels94 Jun 22 '13 at 04:10
  • Interesting. Simple test in IE8 for Win7 shows that `querySelector` is supported http://jsfiddle.net/syNvz/show/ and QSA too http://jsfiddle.net/syNvz/2/show/ – Fabrício Matté Jun 22 '13 at 04:13
  • `document.getElementByID("<%=searchTxt.ClientID %>").value` is also valid and has worked for me when `document.getElementByID("searchText").value` has not. – Amicable Jul 16 '13 at 10:54
  • @Amicable your App. is not HTML and JS.If i am not wrong then you are using ASP right.I don't know ASP so i can't say a lot but the methods given here are general and will work in most of the cases – bugwheels94 Jul 17 '13 at 14:07
  • Your answer is fine as is and you're correct, my app is JS/HTML with Asp.net. The variable wasn't declared in an asp.net control in my case - just thought it may be useful for anyone stumbling across this question. – Amicable Jul 18 '13 at 00:23
  • But where is Method 7 (or better 0): searchTxt.value ? – Grigory Kislin Apr 20 '17 at 20:45
  • @GKislin What do you mean by `searchTxt.value`, may you please create a fiddle or codepen showing the demo? – bugwheels94 Apr 20 '17 at 20:51
  • @ankitbug94 Tested in chrome and FF (work for element id): https://jsfiddle.net/p94ygswy/ And for form this works for elements name: http://www.4stud.info/web-programming/samples/dhtml-calculator.html – Grigory Kislin Apr 26 '17 at 10:25
  • 1
    @GKislin Ah! I see. Nice that I didn't know about it. But after reading [this](http://stackoverflow.com/a/3434388/1533609), I am feeling reluctant to add this edit to the answer right now. Maybe someday later, I will add it with a warning to avoid it. One of all reasons for warning would be [this](https://jsfiddle.net/p94ygswy/4/). If you feel like it is really nice, then either make an edit with a warning or add another answer upon your wish :) – bugwheels94 Apr 26 '17 at 14:05
  • how would you get *all* the occurrences with `getElementsByName`? say there might be more than one index, and i need to get everything from `[0]` to `[20]` – calyxofheld Aug 27 '21 at 07:44
  • 1
    @calyxofheld Either use [forEach](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach) or for loop over all of them. It is very basic thing in JS. Have you gone through JS briefly, if not? then I will recommend you to go through that first. Keep learning – bugwheels94 Aug 28 '21 at 07:36
  • if the user doesnt write anything in input form, but they click the submit button, what return will i get? because i use addeventlistener click to get the value – 057 Ahmad Hilman D Oct 24 '22 at 22:01
  • @057AhmadHilmanD empty string – bugwheels94 Oct 26 '22 at 02:32
  • Method 1 only gets me the original value, if the user types someting else in the input I still get the original value, how to overcome that ? – GuidoG Nov 19 '22 at 08:24
  • 1
    @GuidoG There is some bug in your come most likely – bugwheels94 Nov 19 '22 at 10:48
44
//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.

maudulus
  • 10,627
  • 10
  • 78
  • 117
  • While I appreciate the completeness of the accepted answer, I found this answer to be of use re: accessing, in JS code, a value entered in a DOM text input element (text box). For detail, see my answer, elsewhere in this Question. – Victoria Stuart Apr 05 '17 at 23:51
32

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;

John Smith
  • 851
  • 2
  • 10
  • 22
  • If you want it to be a proper javascript object so that you can programmatically access each property, just do: var input = JSON.parse(document.getElementById("input_id").value); – JakeJ Jul 16 '19 at 13:33
23

You should be able to type:

var input = document.getElementById("searchTxt");

function searchURL() {
     window.location = "http://www.myurl.com/search/" + input.value;
}
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

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.

viana
  • 495
  • 4
  • 18
  • 42
Fredrik
  • 971
  • 8
  • 23
16

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.

Deepend
  • 4,057
  • 17
  • 60
  • 101
user3768564
  • 274
  • 3
  • 9
  • Yes! I was surprised this simplicity. Have a look at realization of simple calculator http://www.4stud.info/web-programming/samples/dhtml-calculator.html Are ther any reference for this javascript functiality, cause I before I always use jQuery or getElementById – Grigory Kislin Apr 20 '17 at 20:37
10

Short

You can read value by searchTxt.value

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

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





<!-- SHORT ugly test code -->
<button class="search" onclick="searchURL()">Search</button>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • The edit is fine; commentary on downvotes doesn't belong in posts. Please refrain from rolling back when the post unlocks – Zoe Nov 28 '21 at 16:46
  • @Kamil - do you know what this short form method is called for getting the data, or do you have some reference to a DOC that exsplains what this is - i've just enouctered this in some code and it had me pooring over the code base for a querySelector somewhere. - this is great as a feature, just so different to the "normal" way of JS interacting with code. Thanks – Wally Sep 08 '22 at 15:36
  • @Wally It's not great. This thing in discussed in comments of few other answers here. https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-properties/3434388#3434388 Why it is not great: https://jsfiddle.net/p94ygswy/4/ – bugwheels94 Sep 19 '22 at 14:41
7
<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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hari Das
  • 10,145
  • 7
  • 62
  • 59
7

You can use onkeyup when you have more than one input field. Suppose you have four or input. Then document.getElementById('something').value is annoying. We need to write four lines to fetch the value of an input field.

So, you can create a function that store value in object on keyup or keydown event.

Example:

<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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dhruv Raval
  • 1,535
  • 1
  • 8
  • 15
6

If your input is in a form and you want to get the value after submit you can do like:

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

Benefit of this way: Example your page have 2 form for input sender and receiver information.

If you don't use form for get value then

  • You can set two different id (or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
  • If you set the same value for two inputs, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later, if you change the order of 2 form in HTML, you need to check this code again

If you use form, then you can use name, address, ...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Linh
  • 57,942
  • 23
  • 262
  • 279
5

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.

From @bugwheels94: when using this method, be aware of this issue.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
5
<input id="new" >
<button  onselect="myFunction()">it</button>
<script>
    function myFunction() {
        document.getElementById("new").value = "a";
    }
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:

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

Source: w3schools

Valter Ekholm
  • 173
  • 2
  • 17
3

function handleValueChange() {
    var y = document.getElementById('textbox_id').value;
    var x = document.getElementById('result');
    x.innerHTML = y;
}

function changeTextarea() {
  var a = document.getElementById('text-area').value;
  var b = document.getElementById('text-area-result');
  b.innerHTML = a;
}
input {
  padding: 5px;
}

p {
  white-space: pre;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>

<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
0

Simple JavaScript:

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
function searchURL() {
   window.location = 'http://www.myurl.com/search/' + searchTxt.value
}

So basically searchTxt.value will return the value of the input field with id='searchTxt'.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
0

Short Answer

You can get the value of text input field using JavaScript with this code: input_text_value = console.log(document.getElementById("searchTxt").value)

More info

textObject has a property of value you can set and get this property.

To set you can assign a new value: document.getElementById("searchTxt").value = "new value"

C2121
  • 81
  • 13