Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default text in input field

I don't know if this has a special name for it, but is there a nice easy way to set default text in an input field which disappears on focus and reappears on blur if the textbox is empty?

like image 232
oshirowanen Avatar asked Feb 01 '11 11:02

oshirowanen


1 Answers

You can use the new HTML5 placeholder attribute.

Edit: update to use some more HTML5/jQuery hotness, HTML5 data storage.

<input type="text" placeholder="type here" data-placeholder-text="type here" />

This will work on all modern browsers. And gracefully degrade in IE. However for IE you'll have to use javascript.

$(document).ready(function() {

    var $input = $('#id_of_input_element');
    $input.focus(function() {
        if($(this).val() == $(this).data('placeholder-text')) { 
            $(this).val('') 
        }
    }).blur(function() {
        if($(this).val() == '') {
            $(this).val($(this).data('placeholder-text'));
        }
    }).trigger('blur');
}):
like image 120
xzyfer Avatar answered Sep 21 '22 01:09

xzyfer