Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #HowTo #Input

How to make an HTML text box show a hint when empty

In this article, we will explore two methods to make an HTML text box display a hint when it's empty.

This feature is handy for guiding users and providing context for the input they should provide. Let's dive in!

Method 1: Using the placeholder Attribute #

The placeholder attribute in HTML allows you to define a hint or sample text that appears within the text box when it's empty.

<input type="text" placeholder="Enter your email address">

Explanation:

  1. The placeholder attribute is applied directly to the input element.
  2. It provides a clear hint to users about the expected input.
  3. The hint text automatically disappears as soon as the user starts typing.

Method 2: Implementing with JavaScript #

If you need more control or dynamic behavior for your hint text, you can use JavaScript.

<input type="text" id="emailInput">
<script>
  const inputElement = document.getElementById("emailInput");
  inputElement.addEventListener("focus", () => {
    inputElement.placeholder = "Enter your email address";
  });
  inputElement.addEventListener("blur", () => {
    inputElement.placeholder = "";
  });
</script>
How to make an HTML text box show a hint when empty

Explanation of the above example:

  1. We give the input element an id to target it with JavaScript.
  2. Using event listeners, we set the placeholder when the input gains focus and remove it when it loses focus.

Conclusion #

In this article, we explored two methods to make an HTML text box display a hint when it's empty: using the placeholder attribute in HTML and implementing it with JavaScript.

save
listen
AI Answer
Write Your Answer
loading
back
View All