Javascript – How to make an HTML text box show a hint when empty


I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.

BTW, this is an on-page Ajax search, so it has no button.

Best Solution

Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's placeholder attribute:

<input name="email" placeholder="Email Address">

In the absence of any styles, in Chrome this looks like:

enter image description here

You can try demos out here and in HTML5 Placeholder Styling with CSS.

Be sure to check the browser compatibility of this feature. Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called jQuery HTML5 Placeholder, and then just add the following JavaScript code to enable it.

$('input[placeholder], textarea[placeholder]').placeholder();