Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text as place holder for textbox input?

I notice that at some websites like http://academia.edu/, the signup form has some "place-holder" in their text input field. Such that in a textbox, there's no label but a rather slight font "First name" word inside the text box.

When using Firebug to investigate, I see the following code:

<input class="standard_text magic-default magic-default-on" id="user_first_name" name="user[first_name]" size="30" type="text" value="First Name">

It looks like there's some "magic" javascript happen behind the scene. But since I'm not familiar with javascript debugging yet, I can't trace out how they do that yet.

Does anyone know how to produce that effect?

like image 807
Hoàng Long Avatar asked Dec 13 '22 07:12

Hoàng Long


2 Answers

For modern browsers you can use the HTML5 placeholder attribute.

This will achieve the result you're after without any Javascript and will scale (won't do anything) in older browsers.

<input placeholder="First Name">

To get this working in older browsers you can include a little bit of jQuery:

$('input:text').focus(function(){
    if ( $( this ).val () === $( this ).attr ( 'placeholder' ) ) { 
      $(this).val('');
    }
}).blur(function(){
    if($(this).val() == "")
    {
        $(this).val($(this).attr('placeholder'))
    }
}
);

Working Example

like image 85
Jamie Dixon Avatar answered Feb 10 '23 12:02

Jamie Dixon


You have to create a "onFocus" event handler for the input box, and clear the value of said input box. Off course you only clear the value if it's the default value ("First Name" in your example), so that you don't clear away whatever user entered if he returns to the input later.

You could also attach a "onBlur" event handler, and restore the value of the input box back to the default value (if user didn't enter anything).

like image 21
Jan Hančič Avatar answered Feb 10 '23 10:02

Jan Hančič