03 October 2009

This is a simple jQuery snippet that will put text (e.g. "Search...") into a text input field based on the alt attribute. This avoids having to compute a default value server-side, and it provides more data to the user at the same time.

The HTML

<input alt="Search..." type="text" />

The jQuery

$(document).ready(function(){
    $('input[alt]:text').click(function(){
        if ($(this).val() == $(this).attr('alt')) {
            $(this).val('');
        }
    }).blur(function(){
        if ($(this).val() == "") {
            $(this).val($(this).attr('alt'));
        }
    }).each(function(){
        $(this).val($(this).attr('alt'));
    });
});

Technologies:


blog comments powered by Disqus