Tuesday 14 July 2009

Placeholder message in input box with jQuery

I love working with jQuery. It's powerfull and relative easy to use. So I use it also for working with placeholder text inside a input textbox in HTML. So, when no text was entered, a default 'help' text/message is shown, like 'Click here to enter your firstname...'
In my case, I just wanted to have the text 'Zoeken...' (Dutch for Search...).
See the following flash demo:


To get this working, I used jQuery.
First of all, I set up the text box like this:

<input type="text" title="Zoeken..." name="search" value="Zoeken..." class="text" />


In the head section of the page, you need a reference to the jquery library:

<script type="text/javascript" src="http://YourUrl/jquery.js"></script>

Just before the end of the head section place the following piece of javascript code and you are done:

$(document).ready(function() {
function switchText()
{
if ($(this).val() == $(this).attr('title'))
$(this).val('');
else if ($.trim($(this).val()) == '')
$(this).val($(this).attr('title'));
}

$('input[type=text][title != ""]').each(
function()
{
if ($.trim($(this).val()) == '')
$(this).val($(this).attr('title'));
}
).focus(switchText).blur(switchText);

$('form').submit(
function()
{
$(this).find('input[type=text][title != ""]').each(
function()
{
if ($(this).val() == $(this).attr('title'))
$(this).val('');
}
);
}
);
});

Remember to put this inside a script tag.

No comments: