I keep writing this little series of Did You Know articles about specific little parts of the CSS, HTML or JavaScript. One little thing to learn, easy to digest and use in your dailywork. Last time it was about Lists and specific attributes like start, reversed and type for ul and ol elements. This time, let’s dive into defaultValue in JS.

Defining defaultValue

As defined in the MDN, the defaultValue property is a string that:

Returns / Sets the default value as originally specified in the HTML that created this object.

In other words, the defaultValue property is the value of an input element as set the first time the HTML document is read. That means you can change the value of the input by typing thing in the field, or edit the value property with JavaScript, the defaultValue will remain the same.

Code example of defaultValue property

Imagine the code of a simple label with input (because you always set a label for your input, right?) like the following:

<label for="input-1">What do you like?</label>
<input type="text" value="Something" id="input-1">

The word “Something” appears in the field, you can edit it and put “Another Value” inside.
Now some JavaScript to retrieve the different values:

let myinput = document.getElementById('input-1');

console.log( myinput.value ); // returns "Another Value"

myinput.value = 'JS Value';

console.log( myinput.value ); // returns "JS Value"
console.log( myinput.defaultValue ); // returns "Something"

You can set the new value by hand or with script, it won’t change de defaultValue value.
Can be really useful when it comes the time to edit data.

I set you a little playground on Codepen if you want to test it and play with it.

See the Pen JavaScript defaultValue demo.1

And defaultChecked for checkbox and radio

The property works exactly the same way than defaultValue. I let you explore more the way you can use it in your context and dailywork, I never had the need to use it for the moment.

Have fun and don’t hesitate to comment!

Cet article est également disponible en : French