How to clear a text area on focus with JavaScript?

Sometimes, we want to clear a text area on focus with JavaScript.

In this article, we’ll look at how to clear a text area on focus with JavaScript.

How to clear a text area on focus with JavaScript?

To clear a text area on focus with JavaScript, we can call the val method with an empty string when we add a focus event handler to the text area with focus.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<textarea>hello world</textarea>

to add a text area.

Then we write:

$('textarea').focus(function() {
   $(this).val('');
});

We select the text area with $.

Then we call focus to add a focus event handler with a function that empties the text area with $(this).val('');.

Therefore, when we click inside the text area, it becomes empty.

Conclusion

To clear a text area on focus with JavaScript, we can call the val method with an empty string when we add a focus event handler to the text area with focus.