How to clear an input field on focus with CSS?


To clear an input field, first create an input filed. To clear, use the onfocus attribute. Let us see with two examples.

Create an Input Field

First, use the input type to create an input field in a form on a web page −

<input type="text" value="Some random text...">

Clear the Input Field on Focus

To clear the input field, use the onfocus attribute.

<input type="text" onfocus="this.value=''" value="Some random text...">

Clear an Input Field on Focus

The following is the code to clear an input field on focus −

<!DOCTYPE html>
<html>
<body>
   <h1>Clearing an input field on focus example</h1>
   <input type="text" onfocus="this.value=''" value="Some random text...">
   <p>Click on the above field to clear its value</p>
</body>
</html>

Clear Input Fields

Let us see an example with multiple input fields. For all of them, we have used the onfocus attribute −

Example

<!DOCTYPE html>
<html>
<head>
   <style>
      input {
         margin: 2%;
         width: 100%;
      }
      div {
         display: flex;
         flex-direction: column;
         margin: 3%;
         padding: 3%;
         text-align: center;
         align-items: center;
         box-shadow: inset 0 0 30px brown;
      }
      button {
         width: 40%;
      }
   </style>
</head>
<body>
   <div>
      <input type="text" onfocus="this.value=''" value="Enter Username"/>
      <input type="email" onfocus="this.value=''" value="somenone@somewhere.com" />
      <button>Submit</button>
   </div>
</body>
</html>

Updated on: 16-Nov-2023

611 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements