Tuesday, 18 February 2014

Default values in ASP Textbox with JQuery

Sometimes you will need to add instructions to textboxes to provide input information to the user. We can use default text to do this. This is the text that will appear in the textbox when it is empty.


Step 1

If you don't have jQuery then download latest library from its website and include in the script section of your page.

<script src="jquery.js" type="text/javascript"></script>
 
Step 2

Next you need to create two CSS classes - defaultText and defaultTextActive as shown below. These are described in Step 3.


<style media="screen" type="text/css">
   .defaultText { width: 300px; }
   .defaultTextActive { color: #a1a1a1; font-style: italic; }
</style>


Step 3

Add the following JavaScript to you page. This associates the CSS classes with the appropriate JQuery methods.

<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 its css class and specify the default text in the title attribute. e.g.
 
<input class="defaultText" title="e.g. someone@example.com" type="text" />

No comments:

Post a Comment