Friday, September 13, 2013

"Default Text" Fields Using Simple jQuery Trick

A lots of the time you want to add instructions to text box fields of the page to provide usability information to the users. Alternate way of doing this could be using default text in the input fields. A default text is the text which appears in the text box when it is empty. e.g.
Name
Email
Website
Comment
You can see this is useful and good idea to have this in the UI. There is an easy trick in jQuery to do this. Below is the step by step procedure to do this.

Step1

If you don't have jQuery then download latest from its website and include in you page.
<script src="jquery.js" type="text/javascript"></script>

Step 2

Create two CSS classes defaultText and defaultTextActive as mentioned below.
<style media="screen" type="text/css">
    .defaultText { width: 300px; }
    .defaultTextActive { color: #a1a1a1; font-style: italic; }
</style>

Step 3

Add this JavaScript to you page
<script language="javascript">
<!--
$(document).ready(function()
{
    $(".defaultText").focus(function(srcc)
    {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    $(".defaultText").blur(function()
    {
        if ($(this).val() == "")
        {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    
    $(".defaultText").blur();        
});
//-->
</script>

Step 4

To every text field or text area where you want to apply default text add "defaultText" as css class and specify the default text in the title attribute. e.g.
<input class="defaultText" title="e.g. someone@example.com" type="text" />
You default text setup is ready. Run the page and see the magic. Click here for a running sample page.

No comments:

Post a Comment