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?
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
document.getElementById('textbox_id').value
to get the value of
desired box
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...
Use
document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
document.getElementsByClassName("searchField")[0].value;
if this is the first textbox in your page.
Use document.getElementsByTagName('tag_name')[whole_number].value
which also returns a live HTMLCollection
document.getElementsByTagName("input")[0].value;
, if this is the first textbox in your page.
document.getElementsByName('name')[whole_number].value
which also >returns a live NodeList
document.getElementsByName("searchTxt")[0].value;
if this is the first textbox with name 'searchtext' in your page.
Use the powerful document.querySelector('selector').value
which uses a CSS selector to select the element
document.querySelector('#searchTxt').value;
selected by iddocument.querySelector('.searchField').value;
selected by classdocument.querySelector('input').value;
selected by tagnamedocument.querySelector('[name="searchTxt"]').value;
selected by namedocument.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.
document.querySelectorAll('#searchTxt')[0].value;
selected by iddocument.querySelectorAll('.searchField')[0].value;
selected by classdocument.querySelectorAll('input')[0].value;
selected by tagnamedocument.querySelectorAll('[name="searchTxt"]')[0].value;
selected by nameSupport
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 |
FF3.5/FF3.6 | Y | Y | Y | Y | Y |
FF4b1 | Y | Y | Y | Y | Y |
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 |
Key:
IE=Internet Explorer
FF=Mozilla Firefox
GC=Google Chrome
Useful links