PUBLISHED ON: AUGUST 26, 2021
How to clear an input field on focus with JavaScript
The <input>
element has various usage on the webpage. It is used to take user input like text, password, email, etc. To clear the input data of the input field user needs to use the backspace or delete key. But we can also clear the input field on focus with JavaScript.
In this tutorial, we will learn to clear the input field on focus.
Clear input field on focus
JavaScript has a onfocus()
event that occurs when the element gets focused. This onfocus()
event can be used to clear the input field. To do so use onfocus="this.value"=" "
within the input field. It will clear the previous value.
Example: Clear input field on focus
Here we have added an input field using <input> tag and added the onfocus()
event to clear the input field on focus.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
<h2> clear input field on focus </h2>
<input type="text" onfocus="this.value=''" value="Click">
</body>
</html>
Output
Here is the output of the above example.
Before focus
The input field has some text
on focus
It gets cleared on focus
Example: Clear input field on focus
We can alternatively use onfocus="this.value='';"
to clear the input on focus. Here is an example to do so.
Conclusion
In this tutorial, we have learned to clear the input field on focus. To do so use JavaScript onfocus()
event and replace the input field with white space. It has been explained with an example in this tutorial.