Thursday, November 17, 2005

Clear default text onClick + restore if nothing entered

Good little javascript snippet from Jennifer/Scriptygoddess to have for when, yeah, exactly, for the days when… :

“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’ 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.”

(Via scriptygoddess –>clear default text onClick - restore if nothing entered.)

No Comments yet »

Leave a comment

authimage

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Subscribe without commenting