Also available in: Français
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:
The word “Something” appears in the field, you can edit it and put “Another Value” inside.
Now some JavaScript to retrieve the different values:
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.
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.
And if you didn’t know, you can style with CSS your checkboxes and radio button. Read Custom Accessible Checkbox and Radio button in CSS article to know how!
Have fun and don’t hesitate to comment!
Post a comment for this article?
Follow comments and trackbacks