15 Nov, 2005
clear default text onClick – restore if nothing entered
Posted by: Jennifer In: Scripts
Still on hiatus but wanted to post a little javascript (mainly for my future reference) I've used a few times in various applications.
One function will clear the "default" text in a field when the user clicks into it. The second function will replace the default text in the field if the field was left blank.
This goes inside the <head></head> tags:
<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value == "") {
thisfield.value = defaulttext;
}
}
</script>
Then you add the following onclick, onblur events to your field. (Shown in bold):
<input type="text" name="myfield" value="default text" onclick="clickclear(this, 'default text')" onblur="clickrecall(this,'default text')" />
Uses? a search field – your "default text" could give clues about what you can search for. ie "Enter keyword or item #". Or it could display the format of the content you want from your user, ie. a date field with this as the default text "MM-DD-YYYY".
Update 11/16/05 Updated script on the suggestion of Joan and Sunny.
Update 11/24/05 Here's another neat way to do this without the "onclick" and "onblur" embedded in the input tag itself.