Monday, 15 April 2013

jQuery: Automatically clear restore form fields


placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the field is focused upon, then hides the text.  You've seen this technique a billion times with JavaScript, but native HTML5 support is even better!

<input type="text" class="clear-it" placeholder="Search for an item here.." />

Job done!!!


jQuery Code:


jQuery.fn.defValue = function(){
    return this.each(function(){
        $(this).focus(function(){
            var defVal = this.defaultValue;
            if($(this).val() == defVal){
                $(this).val('');/* Clear box if it hasnt changed */
            }
        }).blur(function(){
            var defVal = this.defaultValue;
            if($(this).val() == ''){
                $(this).val(defVal);
            }
        });
    });
}
//usage
$(document).ready(function(){
  $('input').defValue();
});

Html: Just add the following text box
<input type="text" class="clear-it" value="Search for an item here.." />

No comments:

Post a Comment