Sometimes, we want to delete the default value of an input text on click with JavaScript.
In this article, we’ll look at how to delete the default value of an input text on click with JavaScript.
How to delete the default value of an input text on click with JavaScript?
To delete the default value of an input text on click with JavaScript, we can set the value of the input to the default by setting the value
attribute and using the defaultValue
property.
For instance, we write:
<input type="text" value="[some default value]" />
to set the value attribute to set the defaultValue
property of the input.
Then we write:
const onBlur = (e) => {
if (e.target.value === '') {
e.target.value = e.target.defaultValue;
}
}
const onFocus = (e) => {
if (e.target.value === e.target.defaultValue) {
e.target.value = '';
}
}
const input = document.querySelector('input')
input.addEventListener('focus', onFocus)
input.addEventListener('blur', onBlur)
to add the onBlur
and onFocus
functions which runs when we focus away and in the input respectively.
In the onBlur
function. we set the value
of the input to the defaultValue
.
And in onFocus
, we set the input’s value
to an empty string if it’s the same as the defaultValue
.
e.target
is the input since we call addEventListener
on the input
that we selected with document.querySelector
.
Conclusion
To delete the default value of an input text on click with JavaScript, we can set the value of the input to the default by setting the value
attribute and using the defaultValue
property.