We often see sites which has a text box with some default value, mostly in grey and when we click inside the textbox, the default value disappears and we can type in, similarly if we click elsewhere in the page the default value again re-appears.

This can be achieved very simply using javascript where we display the default data on onblur event and it disappears on onfocus event, see the illustration below:

Suppose I have a html textbox as follows,

<input id=”txtBizFocus” runat=”server” name=”txtBizFocus” autocomplete=”off” type=”text”  enableviewstate=”true”/>

 Now, I have to check whether txtBizFocus is empty or not, if it is empty include the default value in grey color. Now, if the user clicks inside the textbox txtBizFocus, the default value should disappear and the user should be able to type inside in font-color black.

 if (txtBizFocus.Value == “”)

txtBizFocus.Value = “<type here or select>”;

if (txtBizFocus.Value == “<type here or select>”)

{

    txtBizFocus.Style.Add(“color”, “#808080”);

 

}

else

{

    txtBizFocus.Style.Add(“color”, “black”);

}

 txtBizFocus.Attributes.Add(“onfocus”,   var txtBizFocus = document.getElementById(‘” + txtBizFocus.ClientID + “‘); if(txtBizFocus.value=='<type here or select>’){txtBizFocus.value=”; txtBizFocus.style.color=’black’;};”);

 

txtBizFocus.Attributes.Add(“onblur”,   var txtBizFocus = document.getElementById(‘” + txtBizFocus.ClientID + “‘); if(txtBizFocus.value==”){txtBizFocus.value='<type here or select>’; txtBizFocus.style.color=’#808080′;};”);

 

 So, when the page loads, txtBizFocus comes with a default value “<Type here or select>” in grey color, the moment user clicks inside the textbox(onfocus) the writing disappears and becomes blank so that the user can type in black(this is checked in the above code, where we check if the value inside txtBizFocus is not the default value, change color to black).

Advertisements