Set the Default Value of an Input Field
Here's a quick way to set an input's default value:
This will pre-populate your input field having id="myInput"
with "Preset text goes here" upon load.
Advanced and Alternative Default Value Techniques
Different methods to assign default values to your input fields.
Picking elements with querySelector
Using querySelector provides a flexible way to select elements.
setAttribute: Another approach
You can directly set the value as an attribute using setAttribute
.
Focusing on Forms
When you deal with forms, use above method to specify form and input names directly.
To avoid any DOM-not-fully-loaded-errors, it's advisable to place script tags right before the closing </body>
tag.
Troubleshoot & Uncommon Scenarios
What if my script runs too early?
If DOM isn't fully loaded, use window.onload
:
This waits for the page load before setting the value.
What if I'm using special input types (checkbox/radio)?
For checkboxes or radio buttons:
And, for select elements:
Dynamic? (Changeable at runtime)
How about setting values dynamically:
The Picture of Preloaded Music Box
Preload the melody (value) you want to be played as the box opens.
Adding the User Experience Spice
Placeholder vs Value: The mysterious duality
While value
is the real content of an input, placeholder
is a guide text that vanishes upon focus.
Clearing on interaction: Preventing the deja-vu
Consider clearing the default value as the user starts typing:
The importance of labels: To us, and screen readers
Provide labels for every input for screen readers and improved accessibility:
Was this article helpful?