Jquery Field Replace

< Back to blog | Add a comment

Posted: 15th May 2009
Categories: Tips and Tricks Web Development
Tags: jquery field replace input form switch

It's time for some cool Jquery code, it has been too long - we do apologise.

I've been working on my Jquery Field Replace script which automatically switches the value of an input with the title. This is useful if you want to auto populate an input field to explain what it does but not keep it in there. Code is all yours, but please credit us or at least let us know if you have used it by dropping a comment. Enjoy!


The code:

(function($) {
$.fn.fieldreplace = function(options) {
    var searchelement = this;
    var parentform = $(this).parent('form');
    var oldcolor = $(searchelement).css('color');
    var string = $(searchelement).attr('title');
    $(parentform).submit(function(){
        if ($(searchelement).val() == string)
        $(searchelement).val('');
    });
    $(searchelement).val(string);
    $(searchelement).css({color: '#bbb'});  
    $(searchelement).focus(function(){
        if ($(this).val() == string){
            $(searchelement).css({color: oldcolor});
            $(this).val('');
        }
    });
    $(searchelement).blur(function(){
        if ($(this).val() == ''){
            $(searchelement).css({color: '#bbb'});
            $(this).val(string);
        }
    });
    return true;
}
})(jQuery);

And the usage:

$('#myinput').fieldreplace();

Add a comment









Back to top