Reading input values
Learn to read input values with the value property and check for empty inputs.
The value property
To read the text a user typed into an input field, you use the value property. It returns the field's current value as a string.
const name = document.querySelector('input');
console.log(name.value);An empty field has a value of empty string (''). Even if you expect a number, the browser always returns a string; converting it comes in later lessons.
Empty input check
To catch a user who only pressed the space bar, you use the trim method. trim removes leading and trailing spaces from the value.
const name = input.value.trim();
if (name === '') {
console.log('Empty input');
}This way an input of only spaces also counts as empty. This check is done in almost every validation.
Exercise Read the value, trim it and check
The input variable points to an input field. Read its value, clean it with trim, and log 'Empty input' if it is empty; otherwise log the value.
Show example solution
const value = input.value.trim();
if (value === '') {
console.log('Empty input');
} else {
console.log(value);
}
Test yourself
-
Trim the value
const input = document.querySelector('input'); const value = input.value.____(); if (value === '') { console.log('Empty'); }Show answer
const input = document.querySelector('input'); const value = input.value.trim(); if (value === '') { console.log('Empty'); } -
Match properties to their meanings
- input.value
- The field's text
- value.trim()
- Removes spaces
- value === ''
- Empty input check
-
Which correctly reads the input value?
const input = document.querySelector('input'); // A const a = input.text; // B const b = input.content; // C const c = input.value; // D const d = input.data;- A
- B
- C
- D
Show answer
C — Correct! input.value gives the field's current text.