Wednesday, May 1, 2013

Add a label inside a textfield in a HTML form with basic javascript


Have you come across a situation when you have designed a form for your page and you forgot to add the labels for the input field. Or you just want a compact form with the labels inside the input textfield itself. Then don't worry you don't require to break your head and change the css styles or the design.

Using basic javascript you can accomplish the feat of putting the label inside the text input field.

Check the below code which displays the label inside the text input field :

<input name="username" type="text" value="Username">

When you click on the input field the label will disappear. What if you want show the label as the user may forget what the label was.

So it should work as such that when user clicks on the input field the label goes but when again the user clicks on the any other part of the label should be visible again.

We can make use of the onfocus and onblur event in javascript :

<input name="username" onfocus="if (this.value=='Username') this.value = ''" onblur="if (this.value=='') this.value = 'Username'" type="text" value="Username">

If we have big label then we can use another method to reduce the javascript size by using this.defaultValue :

<input name="username" type="text" value="Search" onfocus="if(this.value==this.defaultValue)this.value=''" onblur="if(this.value=='')this.value=this.defaultValue">


Programming

No comments:

Post a Comment