JavaScript

Prepopulating Textarea With Hint Using JavaScript

Over the web, at one point of the time or the other, you may have seen websites in which a textarea shows some default value, such as “Enter your comments” and when you click inside of this textarea, this default value vanishes. This is default value is called a “Textarea Hint” as it serves the purpose of a hint and tells you what to do by doing so. Do you know how to make a textarea behave so? If not, then this article sis for you. In this article, I am going to share an easy way to show, disappear and again show textarea hint based upon whether an input is entered in it or not using JavaScript.

How To Prepopulate Textarea With Custom Hint Using JavaScript

Let’s assume that we have a textarea in a form on our page. Now instead of hardcoding the value inside it, we will populate the textarea hint based upon the onfocus and onblur events. Consider the following example:

Example 1: Prepopulate Textarea with Hint and Lose Hint forever once any input has been entered or entered and removed

<textarea name="message1" cols="25" rows="5" id="area" onclick="document.getElementById('area').innerHTML='';" >Enter your message here</textarea>

Example 2: Prepopulate Textarea with Hint and Restore Default Hint even if the input has been entered  and removed

<textarea name="message2" cols="25" rows="5" id="message2" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;">Enter your message here</textarea>
That’s it!

Do you know of any other ways to show / hide textarea hint using JavaScript? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*