How to clear default text field value in a form with Javascript

JavaScript

<input id=”id” title=”Click to enter missing mandatory information” name=”id” type=”text” value=”Missing value!” onClick=”if(this.value==’Missing value!’){this.value=”;this.className=”;}” onblur=”if(this.value==”){this.value=’Missing value!’;this.className=’empty_text_field’;}” />

The idea here is that ‘onClick’ checks if the default value is in the field.
If it is, it clears the text field when you click on it. So if you type in anything else in the field, it will stay there.

CSS

I also added some CSS that changes the field to bright red if there’s missing information. It also turns to default styling as JavaScript removes the CSS class name.

Here’s the css:

.empty_text_field
{
border:2px solid red; /* Colours the text field border */
color:red; /* Colours the text */
}

Example

‘Missing Value!’ is the default text

An example of a text field default value being cleared via Javascript onClick attribute

 

Your questions

If any, please ask!!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s