Categories
JavaScript Answers

How to delete default value of an input text on click with JavaScript?

Spread the love

Sometimes, we want to delete default value of an input text on click with JavaScript.

In this article, we’ll look at how to delete default value of an input text on click with JavaScript.

How to delete default value of an input text on click with JavaScript?

To delete default value of an input text on click with JavaScript, we set the value property.

For instance, we write

<input
  type="text"
  value="[some default value]"
  onblur="onBlur(this)"
  onfocus="onFocus(this)"
/>

to add an input.

Then we write

function onBlur(el) {
  if (el.value === "") {
    el.value = el.defaultValue;
  }
}
function onFocus(el) {
  if (el.value === el.defaultValue) {
    el.value = "";
  }
}

to set the input’s value property to an empty string to empty the input box in the onFocus function when value is the same as defaultValue.

We set onfocus to onFocus(this) call it when we focus on it.

And we set onblur to onBlur(this) call it when we move focus away from it.

Conclusion

To delete default value of an input text on click with JavaScript, we set the value property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *