Let us say you have the following text input field.
<input name="searchBox" type="text" id="searchTxt" class="searchField"/>
1. Using ID
You can easily get value of text input field using its id attribute. Here is an example to get input field value using its ID. Replace the part in bold below with the ID of your input text.
var input_value = document.getElementById("searchTxt").value;
2. Using Class Name
You can also use the class name to identify the text input field. Here is syntax to get text input field value using its class name.
Here is an example of it. Replace searchField with the class name of your text input field.
var input_value = document.getElementsByClassName("searchField").value;
Also you need to replace 0 above with the index of your input. This is because getElementsByClassName returns a collection of all DOM elements on your page, with matching class name. So you need to specify the exact index of your target element. In our example, we need the first element with matching class so we use 0 index value.
3. Using Tag Name
You can also use tag name to identify the element on your page, with the help of getElementsByTagName() function. Here is the syntax of that command.
Here is an example to get input field.
Here also we need to specify the index number (e.g. 0) to get the first element with matching tag name (e.g. input). This is because getElementsByTagName will return a collection of all DOM elements on your page that match the given tag name.
4. Using Name Attribute
You can get input field value by selecting via its name attribute. Here is the syntax of such a command.
Here is an example to get value of 1st text input field with name=searchTxt.
getElementsByName() function returns a collection of elements whose name matches given value. So we need to specify the index number of the element. We have specified 0 above to get the 1st matching element whose name is searchTxt.
In this article, we have learnt how to get text input field value. Methods 2, 3, 4 require you to specify an index because there can be multiple elements with same class, tag or name attributes on a singe page, and you need to specify the exact element whose value you want.