Form validation - verify that the values make sense and immediately show an error message
Can disable submitting the form and have our program handle the input
Text fields
Fields that contain text such as <input type="text">, <textarea>, etc, share a common interface
These DOM elements have a value property that holds their current content as a string
Setting this property to another string changes the field’s content
selectionStart and selectionEnd
Provide information about the cursor and selection in the text
When nothing is selected, these two properties hold the same number, indicating the position of the cursor
0 indicates the start of the text, and 10 indicates the cursor is after the 10th character
When part of the field is selected, the two properties will differ, giving us the start and end of the selected text.
These properties may also be written to
Example
Imagine you are writing an article about Khasekhemwy but have some trouble spelling his name. The following code wires up a <textarea> tag with an event handler that, when you press F2, inserts the string “Khasekhemwy” for you.
<textarea></textarea><script>let textarea = document.querySelector('textarea');
textarea.addEventListener('keydown', (event) => {
if (event.key === 'F2') {
replaceSelection(textarea, 'Khasekhemwy');
event.preventDefault();
}
});
functionreplaceSelection(field, word) {
letfrom = field.selectionStart,
to = field.selectionEnd;
field.value = field.value.slice(0, from) + word + field.value.slice(to);
field.selectionStart = from + word.length; // Put the cursor after the word
field.selectionEnd = from + word.length;
}
</script>
Explanation of Example
replaceSelection
replaces the currently selected part of a text field with the given word an
then moves the cursor after that word
The keydown event fires when a key is pressed
change Event
The change event for a text field fires when the field loses focus after its content was changed
To respond immediately to changes in a text field, you should register a handler for the input event
fires every time the user types a character, deletes text, or otherwise changes the field’s content
Counter Example
The following example shows a text field and a counter displaying the current length of the text in the field:
<inputtype="text" /> length: <spanid="length">0</span><script>let text = document.querySelector('input');
let output = document.querySelector('#length');
text.addEventListener('input', () => {
output.textContent = text.value.length;
});
</script>