[javascript] How do I 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.

This question is related to javascript html

The answer is


When the page first loads, have Search appear in the text box, colored gray if you want it to be.

When the input box receives focus, select all of the text in the search box so that the user can just start typing, which will delete the selected text in the process. This will also work nicely if the user wants to use the search box a second time since they won't have to manually highlight the previous text to delete it.

<input type="text" value="Search" onfocus="this.select();" />

I posted a solution for this on my website some time ago. To use it, import a single .js file:

<script type="text/javascript" src="/hint-textbox.js"></script>

Then annotate whatever inputs you want to have hints with the CSS class hintTextbox:

<input type="text" name="email" value="enter email" class="hintTextbox" />

More information and example are available here.


I found the jQuery plugin jQuery Watermark to be better than the one listed in the top answer. Why better? Because it supports password input fields. Also, setting the color of the watermark (or other attributes) is as easy as creating a .watermark reference in your CSS file.


Use jQuery Form Notifier - it is one of the most popular jQuery plugins and doesn't suffer from the bugs some of the other jQuery suggestions here do (for example, you can freely style the watermark, without worrying if it will get saved to the database).

jQuery Watermark uses a single CSS style directly on the form elements (I noticed that CSS font-size properties applied to the watermark also affected the text boxes -- not what I wanted). The plus with jQuery Watermark is you can drag-drop text into fields (jQuery Form Notifier doesn't allow this).

Another one suggested by some others (the one at digitalbrush.com), will accidentally submit the watermark value to your form, so I strongly recommend against it.


$('input[value="text"]').focus(function(){ 
if ($(this).attr('class')=='hint') 
{ 
   $(this).removeClass('hint'); 
   $(this).val(''); 
}
});

$('input[value="text"]').blur(function(){
  if($(this).val() == '')
  {
    $(this).addClass('hint');
    $(this).val($(this).attr('title'));
  } 
});

<input type="text" value="" title="Default Watermark Text">

User AJAXToolkit from http://asp.net


Here's a functional example with Google Ajax library cache and some jQuery magic.

This would be the CSS:

<style type="text/stylesheet" media="screen">
    .inputblank { color:gray; }  /* Class to use for blank input */
</style>

This would would be the JavaScript code:

<script language="javascript"
        type="text/javascript"
        src="http://www.google.com/jsapi">
</script>
<script>
    // Load jQuery
    google.load("jquery", "1");

    google.setOnLoadCallback(function() {
        $("#search_form")
            .submit(function() {
                alert("Submitted. Value= " + $("input:first").val());
                return false;
        });

        $("#keywords")
            .focus(function() {
                if ($(this).val() == 'Search') {
                    $(this)
                    .removeClass('inputblank')
                    .val('');
                }
            })
            .blur(function() {
                if ($(this).val() == '') {
                    $(this)
                    .addClass('inputblank')
                    .val('Search');
                }
            });
    });
</script>

And this would be the HTML:

<form id="search_form">
    <fieldset>
        <legend>Search the site</legend>
            <label for="keywords">Keywords:</label>
        <input id="keywords" type="text" class="inputblank" value="Search"/>
    </fieldset>
</form>

I hope it's enough to make you interested in both the GAJAXLibs and in jQuery.


You can add and remove a special CSS class and modify the input value onfocus/onblur with JavaScript:

<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">

Then specify a hint class with the styling you want in your CSS for example:

input.hint {
    color: grey;
}

I'm using a simple, one line javascript solution which works great. Here is an example both for textbox and for textarea:

    <textarea onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">Text</textarea>

    <input type="text" value="Text" onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">

only "downside" is to validate at $_POST or in Javascript validation before doing anything with the value of the field. Meaning, checking that the field's value isn't "Text".


I like the solution of "Knowledge Chikuse" - simple and clear. Only need to add a call to blur when the page load is ready which will set the initial state:

$('input[value="text"]').blur();

For jQuery users: naspinski's jQuery link seems broken, but try this one: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/

You get a free jQuery plugin tutorial as a bonus. :)


You want to assign something like this to onfocus:

if (this.value == this.defaultValue)
    this.value = ''
this.className = ''

and this to onblur:

if (this.value == '')
    this.value = this.defaultValue
this.className = 'placeholder'

(You can use something a bit cleverer, like a framework function, to do the classname switching if you want.)

With some CSS like this:

input.placeholder{
    color: gray;
    font-style: italic;
}

Use a background image to render the text:

 input.foo { }
 input.fooempty { background-image: url("blah.png"); }

Then all you have to do is detect value == 0 and apply the right class:

 <input class="foo fooempty" value="" type="text" name="bar" />

And the jQuery JavaScript code looks like this:

jQuery(function($)
{
    var target = $("input.foo");
    target.bind("change", function()
    {
        if( target.val().length > 1 )
        {
            target.addClass("fooempty");
        }
        else
        {
            target.removeClass("fooempty");
        }
    });
});

Simple Html 'required' tag is useful.

<form>
<input type="text" name="test" id="test" required>
<input type="submit" value="enter">
</form>

It specifies that an input field must be filled out before submitting the form or press the button submit. Here is example



You can use a attribute called placeholder="" Here's a demo:

<html>
<body>
// try this out!
<input placeholder="This is my placeholder"/>
</body>
</html>


You could easily have a box read "Search" then when the focus is changed to it have the text be removed. Something like this:

<input onfocus="this.value=''" type="text" value="Search" />

Of course if you do that the user's own text will disappear when they click. So you probably want to use something more robust:

<input name="keyword_" type="text" size="25"  style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">

The best way is to wire up your JavaScript events using some kind of JavaScript library like jQuery or YUI and put your code in an external .js-file.

But if you want a quick-and-dirty solution this is your inline HTML-solution:

<input type="text" id="textbox" value="Search"
    onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}" 
    onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />

Updated: Added the requested coloring-stuff.


Now it become very easy. In html we can give the placeholder attribute for input elements.

e.g.

<input type="text" name="fst_name" placeholder="First Name"/>

check for more details :http://www.w3schools.com/tags/att_input_placeholder.asp


That is known as a textbox watermark, and it is done via JavaScript.

or if you use jQuery, a much better approach:


This is called "watermark".

I found the jQuery plugin jQuery watermark which, unlike the first answer, does not require extra setup (the original answer also needs a special call to before the form is submitted).


You can set the placeholder using the placeholder attribute in HTML (browser support). The font-style and color can be changed with CSS (although browser support is limited).

_x000D_
_x000D_
input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}_x000D_
input[type=search]:-moz-placeholder { /* Firefox 18- */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}_x000D_
input[type=search]::-moz-placeholder { /* Firefox 19+ */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}_x000D_
input[type=search]:-ms-input-placeholder { /* IE (10+?) */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}
_x000D_
<input placeholder="Search" type="search" name="q">
_x000D_
_x000D_
_x000D_