jQuery – Helpful Default Input Values

I’ve recently wanted to try and use some different code to add some default values to my input fields, especially the search box.  Most code I’ve seen does some type of a label overlay which involved a lot of freaking code.  I finally found some code and did a little tweaking to it to fit my situation.  You can also find it under my Snipplr code.

$(function(){
$('input[type="text"]').each(function(){
if(this.value==''){this.value='Enter Value'}
});
$('input[type="text"]').focus(function(){
if(this.value=='Enter Value'){this.value=''}
});
$('input[type="text"]').blur(function(){
if(this.value==''){this.value='Enter Value'}
});
});

The first part of the code identifies that if the value of the input field is empty add ‘Enter Value’. The second part of the code removes the value ‘Enter Value’ from input fields as it gains focus. The last part of the code adds ‘Enter Value’ to empty fields as they lose focus. This code may not work in every situation, but it can help in some situations. Let me know how it works and if you found other modifications of the code that work even better. This is a dependent on jQuery but I’m sure you may find a version that can adapt to other libraries or straight JavaScript.

This entry was posted in Javascript, jQuery. Bookmark the permalink.

About Brandon Buttars

I am a web designer, search engine optimizer, blogger, writer, graphic designer, wannabe programmer, blah blah internet guru. I do just about everything required in building websites and applications. I'm also a father to 2 boys, soon to be 3, and married happily to my wonderful wife. I'm trying to balance my personal life and my entrepreneurial tendencies.

3 Responses to jQuery – Helpful Default Input Values

  1. Jordan says:

    Perfect, should come in pretty handy.

  2. I am impressed with this site, really I am a big fan .

  3. Some truly nice stuff on this website , I enjoy it.

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>