By user979331


2012-07-19 15:00:28 8 Comments

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?

13 comments

@Phan Van Linh 2019-11-09 08:24:26

If your input is in a form and you want to get 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 2 different id(or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
- If you set same value for 2 input, 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, ...

@Hari Das 2013-06-11 09:32:41

Try this one

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

@Fredrik A. 2014-06-01 22:17:59

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.

@Ricardo Luis Zuluaga Salazar 2019-01-17 13:14:59

simple js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

@Dhruv Raval 2018-12-11 05:12:52

You can use onkeyup when you have more input field. Suppose you have four or input.then document.getElementById('something').value is annoying. we need to write 4 lines to fetch value of 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 first name from object
        console.log(data); //return object
    }
</script>

@Valter Ekholm 2018-07-04 07:29:02

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

@Davinder Singh 2018-03-07 17:47:44

<input id="new" >
    <button  onselect="myFunction()">it</button>    
    <script>
        function myFunction() {
            document.getElementById("new").value = "a";    
        }
    </script>

@GKislin 2017-04-26 10:47:29

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.

@Ranjeet Rana 2015-02-05 05:47:20

If you are using jQuery then by using plugin formInteract, you just need to do this:

// Just keep the HTML as it is.

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

At bottom of the page just include this plugin file and write this code:

// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();

search.getAjax("http://www.myurl.com/search/", function(rsp){
    // Now do whatever you want to with your response
});

Or if using a parameterized URL then use this:

$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
    // Now do work with your response;
})

Here is the link to project https://bitbucket.org/ranjeet1985/forminteract

You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.

Of course I am the author of this project and all are welcome to make it better.

@Hanna 2015-05-18 16:23:22

You should probably mention that this is your own personal plugin.

@Vincenzo 2019-01-17 13:33:10

There is a typo in code snippets. In the second part of code, a double quote is missing.

@bugwheels94 2012-07-19 15:02:14

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

@Fabrício Matté 2013-06-22 04:02:33

IE8 supports QSA as far as I can see, it just doesn't support CSS3 selectors in the selector string.

@bugwheels94 2013-06-22 04:10:26

@FabrícioMatté i just checked here quirksmode.org/dom/tests/basics.html#querySelectorAll and it told me that it doesnot

@Fabrício Matté 2013-06-22 04:13:00

Interesting. Simple test in IE8 for Win7 shows that querySelector is supported jsfiddle.net/syNvz/show and QSA too jsfiddle.net/syNvz/2/show

@Amicable 2013-07-16 10:54:45

document.getElementByID("<%=searchTxt.ClientID %>").value is also valid and has worked for me when document.getElementByID("searchText").value has not.

@bugwheels94 2013-07-17 14:07:23

@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

@Amicable 2013-07-18 00:23:44

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.

@Andy 2016-12-08 17:47:10

Extremely helpful document, saved for reference. Thanks.

@GKislin 2017-04-20 20:45:40

But where is Method 7 (or better 0): searchTxt.value ?

@bugwheels94 2017-04-20 20:51:13

@GKislin What do you mean by searchTxt.value, may you please create a fiddle or codepen showing the demo?

@GKislin 2017-04-26 10:25:25

@ankitbug94 Tested in chrome and FF (work for element id): jsfiddle.net/p94ygswy And for form this works for elements name: 4stud.info/web-programming/samples/dhtml-calculator.html

@bugwheels94 2017-04-26 14:05:10

@GKislin Ah! I see. Nice that I didn't know about it. But after reading this, 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. If you feel like it is really nice, then either make an edit with a warning or add another answer upon your wish :)

@maudulus 2014-11-04 22:34:10

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

@Victoria Stuart 2017-04-05 23:51:51

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.

@Vadim Tatarnikov 2015-06-04 07:12:10

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;

@JakeJ 2019-07-16 13:33:08

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

@user3768564 2014-06-23 18:10: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.

@GKislin 2017-04-20 20:37:05

Yes! I was surprised this simplicity. Have a look at realization of simple calculator 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

Related Questions

Sponsored Content

88 Answered Questions

[SOLVED] How to validate an email address in JavaScript

41 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

88 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6152552 View
  • 7678 Score
  • 88 Answer
  • Tags:   javascript arrays

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

47 Answered Questions

3 Answered Questions

73 Answered Questions

[SOLVED] How can I get query string values in JavaScript?

30 Answered Questions

[SOLVED] How to change an element's class with JavaScript?

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2483053 View
  • 2656 Score
  • 30 Answer
  • Tags:   javascript html dom

Sponsored Content