Explain Codes LogoExplain Codes Logo

Set the Default Value of an Input Field

javascript
input-fields
default-values
user-experience
Nikita BarsukovbyNikita Barsukov·Aug 15, 2024
TLDR

Here's a quick way to set an input's default value:

document.getElementById('myInput').value = 'Preset text goes here';

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

document.querySelector('input[name="userName"]').value = 'Default User';

Using querySelector provides a flexible way to select elements.

setAttribute: Another approach

document.getElementById('userInput').setAttribute('value', 'John Doe');

You can directly set the value as an attribute using setAttribute.

Focusing on Forms

document.forms['userForm']['userName'].value = 'John Doe';

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:

window.onload = function() { document.getElementById('commentField').value = 'Leave a comment'; };

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:

document.getElementById('agreeToTerms').checked = true; // It's like I've read the terms and conditions :)

And, for select elements:

document.getElementById('chooseOption').selectedIndex = 2; // It's magic! The third option is selected by default

Dynamic? (Changeable at runtime)

How about setting values dynamically:

function setDynamicDefault(inputId, defaultValue) { var ip = document.getElementById(inputId); if (!ip.value) { ip.value = defaultValue; } } setDynamicDefault('dynamicInput', 'Dynamic text here...');

The Picture of Preloaded Music Box

<input type="text" value="Default Melody">

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:

var inp = document.getElementById('commentField'); inp.onfocus = function() { if (inp.value == 'Type your comment') { inp.value = ''; // Cleared like my browser history } }; inp.onblur = function() { if (inp.value == '') { inp.value = 'Type your comment'; // Ressurected the default text } };

The importance of labels: To us, and screen readers

Provide labels for every input for screen readers and improved accessibility:

<label for="commentField">Your thoughts:</label> <input type="text" id="commentField" value="Type your comment">