Clear Input Field Value When Selected?

Today’s post will be partially just for my own reference but I’m sure many of you will find it useful and potentionally use it at your websites. There’s a little useful JavaScript function that clears input field once you select it. Imagine you want to have a search input field at your website that says something like “To search type and hit enter” or similar but you want it to clear up once you click at it. It’s pretty simple. Add this to the header:

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

Ok now move to the form where the input field is located. For example, my search form here at Net Covered looks like this:

<form method=”get” action=”<?php bloginfo(‘home’); ?>/”>
<input type=”text” name=”s” id=”searchform” value=”To search – type and hit enter…” onclick=”clickclear(this, ‘To search – type and hit enter…‘)” onblur=”clickrecall(this,’To search – type and hit enter…‘)” />
</form>

The trick is that all three values (I have bolded them) must be the same or else it won’t work. See? That’s it. Now you can try it at your website.

This entry was posted in Miscellaneous and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>