Clear Input Field When Selected

About Us

SEO Web Tips is a regularly updated blog providing search engine optimization tips, tricks and tutorials. We hope you will find many useful web design and development ideas here as well. Thanks for dropping by and please consider subscribing to our blog feed or better subscribing by email for daily updates. More »




Clear Input Field When Selected

If you have tried searching for something on our blog, you might have noticed an interesting little thing. Once you click on the search input field, it clears up. Then, once you deselect it, it fills up with the default value again. This useful effect can be achieved with a very simple JavaScript code (containing just two short functions). Here it goes (you can see it in the header part of the source code, too):

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


Now you will need to adjust your input field a bit. Don’t worry, it’s simple. You will only need to add a default value few times. For example, bellow is code of our search input field (the default value is Search our blog…).

<input type="text" value="Search our blog..." name="s" id="s" onclick="clickclear(this, 'Search our blog...')" onblur="clickrecall(this, 'Search our blog...')" />

That’s it. Pretty simple, don’t you think?

  1. Gabe Says:   

    Wouldn’t it be better to leave the text they type in, and just set back to default text if the input is empty?

    if (thisfield.value.length == "") {
      thisfield.value = defaulttext;
    }

  2. admin Says:   

    Yeah now that I think about it I guess that’s a better solution. Thanks for the tip Gabe ;)

  3. seosoeasy Says:   

    ya its true working.i tried it.hope so good work.iam very glad to say to work here because daily iam coming to know some useful updates.thank you

  4. Underwater Camera Says:   

    Ya,its really pretty simple I agree with you.But will try it later.Thanks

Name (required) 
Email (required) (will not be published) 
Website 
Comment (all comments will be manually reviewed before approval)