JavaScript: How to read a value from a textbox?

HTML forms are everywhere and so textbox. As a developer, you have to deal with a textbox in your everyday development work, even if it is a contact form, login form, billing information, or address information. If you start learning JavaScript from any institute near you, they will also tell teach you to read a value from textbox. And if I am honest with you, getting value from a textbox is a one-line or 3 words of code, check this yourself.

document.getElementById("uName").value;

More Methods

Using Class Name

document.getElementsByClassName("buyPrice")[0].value;

Using tag name

document.getElementsByTagName('input')[0].value

Using control name

document.getElementsByName('searchText')[0].value

Using query selector

document.querySelector('selector').value
document.querySelector('#uName').value;

document.querySelector('.buyPrice').value;

document.querySelector('input').value;

document.querySelector('[name="searchTxt"]').value;

Code Explanation

We are going to look at the syntax of getting a textbox value using JavaScript then we will understand each word in this line of code.

Syntax

<element>.<function>(<selector>)<[Optional array index]>.value;

Whenever we need to take input from a user which is usually required in most websites around the world, we have to read the value from the textbox to save and process it.

If you have a textbox in HTML file like this

<input type="text" id="uName" placeholder="Enter User Name" />

then, you can type following code in JavaScript to read value from the above textbox

document.getElementById("uName").value;

Notice the name of function we used getElementById which has camel casing that means only first letter of the whole function name is small and every other word like Element, By, and Id has first letter capital.