Read Input with JavaScript Summary
JavaScript can read the text inside an input field. This lets a webpage use information that someone enters, such as a name, search term, quantity, or answer.
The text inside an input is called its value. JavaScript can find the input, read its value, and use that information somewhere else on the page.
How to Read an Input Value
First, the HTML needs an input for JavaScript to find. This input has an ID attribute named nameInput and a starting value of Maya.
<input id="nameInput" type="text" value="Maya">
JavaScript can read that value and place it inside a paragraph with one line:
document.querySelector('#message').textContent = document.querySelector('#nameInput').value;
When this code runs, the paragraph displays Maya, the value stored in the input.
Find the Input
This part finds the input on the page:
document.querySelector('#nameInput')
querySelector() finds an HTML element using a CSS selector. The #nameInput selector finds the element with id="nameInput".
Read the Value
The value property gives JavaScript the text currently stored in the input:
document.querySelector('#nameInput').value
If the input contains Maya, this code reads Maya. If the input contains different text, JavaScript reads that text instead.
Display the Input Value
The beginning of the complete line finds a paragraph and uses textContent to replace its text:
document.querySelector('#message').textContent =
The equals sign gives the paragraph the value read from the input. This combines the same text change used in the Change Text lesson with the new value property.
When Websites Read Inputs
Websites read inputs whenever they need to use information entered by a person.
- Display a name in a message.
- Use words entered into a search field.
- Calculate a total from a quantity.
- Check an answer entered into a form.
The example on this page reads the starting value when the page loads. It does not update again when someone types in the field.
Try a Different Value
In the sandbox HTML, replace Maya with another name. Select Update Code, and JavaScript will read the new starting value and display it below the field.
You can also change the input ID, but the selector in the JavaScript must match it exactly or JavaScript will not find the field.