JavaScript Tip: Get the value of a text input field
P粉283559033
2023-08-21 10:35:51
<p>I'm using JavaScript to search. I want to use a form but it will break other things on my page. I have this input text field: </p>
<pre class="brush:html;toolbar:false;"><input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField" />
</pre>
<p>This is my JavaScript code: </p>
<pre class="brush:js;toolbar:false;"><script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" (input text value);
}
</script>
</pre>
<p>How to pass the value of a text field to JavaScript? </p>
View this feature in codepen.
There are several ways to get the value of the input text box directly (without wrapping the input element inside a form element):
method 1
document.getElementById('textbox_id').value
Get the value of the required boxFor example
document.getElementById("searchTxt").value;
Note: Methods 2, 3, 4 and 6 return a collection of elements, so use [integer] to get the required elements. For the first element, use
[0]
, for the second element, use[1]
, and so on...Method 2
Use
document.getElementsByClassName('class_name')[integer].value
, which returns a real-time HTMLCollectionFor example
document.getElementsByClassName("searchField")[0].value;
, if this is the first text box on the page.Method 3
Use
document.getElementsByTagName('tag_name')[integer].value
, which also returns a live HTMLCollectionFor example
document.getElementsByTagName("input")[0].value;
, if this is the first text box on the page.Method 4
document.getElementsByName('name')[integer].value
, it also returns a real-time NodeListFor example
document.getElementsByName("searchTxt")[0].value;
, if this is the first text box named 'searchtext' on the page.Method 5
Use the powerful
document.querySelector('selector').value
, which uses CSS selectors to select elementsFor example
document.querySelector('#searchTxt').value;
Select by iddocument.querySelector('.searchField').value;
Select by classdocument.querySelector('input').value;
Select by tag namedocument.querySelector('[name="searchTxt"]').value;
Select by nameMethod 6
document.querySelectorAll('selector')[integer].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;
Select by iddocument.querySelectorAll('.searchField')[0].value;
Select by classdocument.querySelectorAll('input')[0].value;
Select by tag namedocument.querySelectorAll('[name="searchTxt"]')[0].value;
Select by namesupport