Javascript - Delete a field of a form when clicking (focus)

October 2016

Webmasters can add functionality to web pages by incorporating Javascript into the HTML code. Javascript is a scripting language that is used to write scripts which accomplish certain tasks such as deleting a field on HTML by clicking or focusing on it. Sometimes, HTML forms contain data or prefilled values to provide an example of acceptable data. The form should clear as soon as it is selected for data entry. To delete a field by clicking you need javascript embedded in the HTML code which will erase the contents of the field.


You will often have to input data into HTML forms where there is already data present for some or all of the fields. While it can sometimes be useful to have data automatically inserted where certain information is expected, it can be frustrating when you have to repeatedly delete data to make way for you to enter new information.


It is possible to remove it as soon as the user selects the field using this code:

<form  ... >      
<input type="text" name="name" size=16 value="Enter your name" onFocus="javascript:this.value=''" />      
<input type="submit" value="Validate" />      

But using this method will mean all the text is erased, regardless of what is entered. You can use a condition to replace the text only if the value is "Enter your name":
<input onclick="if(this.value=='Enter your name)this.value=''; ... />

Related :

This document entitled « Javascript - Delete a field of a form when clicking (focus) » from CCM ( is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.