How to Clear Textbox in JavaScript

Anika Tabassum Era Feb 02, 2024
How to Clear Textbox in JavaScript

There is no direct method or property to erase a value in a textbox in JavaScript. The basic assumption is you want to hide or obliterate the placeholder that is by default previewed.

Here, we will give an example of clearing a textbox with JavaScript.

Use the onfocus Attribute to Clear a Textbox

For instance, we will set a value to the input textbox, triggering the function vanish() by setting it to the HTML attribute onfocus. Later in the script section, we disclose the vanish() function that will take the input id.

Then we generate a simple if statement that will check the value to be true and set the value to be blank again.

Code Snippet:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    input{
      color:gray;
    }
  </style>
</head>
<body>
  <input type="text" value="Enter value" onfocus="vanish()" id="input">
  <script>
  function vanish(){
    input = document.getElementById("input");
    if(input.value=="Enter value"){
      input.value = '';
    }
  }
  </script>
</body>
</html>

Output:

Use onfocus Attribute to Clear a Textbox1

Once you click the textbox, the Enter Value will be cleared automatically.

Use onfocus Attribute to Clear a Textbox2

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Textbox