Question

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.

Was it helpful?

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();

OTHER TIPS

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

or if you use jQuery, a much better approach:

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).

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

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;
}

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.

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.

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.

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

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. :)

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.

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).

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.

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");
        }
    });
});

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">

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 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();

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;
}
$('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">

Simple Html 'required' tag is useful.

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

User AJAXToolkit from http://asp.net

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top