Grow your CSS skills. Land your dream job.

Last updated on:

Set/Clear Default Input Value

$('.default-value').each(function() {

       var default_value = this.value;

       $(this).focus(function(){
               if(this.value == default_value) {
                       this.value = '';
               }
       });

       $(this).blur(function(){
               if(this.value == '') {
                       this.value = default_value;
               }
       });

});

Comments

  1. This is very old snippet. Now you better use placeholder or equiwalent. And one important thing – whats about send value? You set the default, but sometimes this is wrong.

    • Andre
      Permalink to comment#

      Considering ‘placeholder’ is part of HTML5, this JS method would be a safe fall back for older browsers…

      Not sure what the problem with the ‘send value’ is though; if the field is empty this will apply the input tag’s default ‘value’, if the field is not empty then it holds whatever was entered.

  2. With my form, I have fields that are not required but have pre-filled value text as a usability hint. Several of these fields go through various types of validation (right number of characters, etc).

    How would i clear only the default value of those specific fields?

    example:

    <input value="Enter promotion code" maxlength="40" title="Promotion Code 1">

    I need to clear the “Enter promotion code” on submit so that the value doesn’t go through validation and trigger an alert.

    • Andre
      Permalink to comment#

      If you are aiming at newer browsers (or if accommodating older browsers is not a problem) it would be better to set it up like this:
      [code][/code]

      Although, to use this JS method, include the provided script in your page and use the following:
      [code][/code]

    • Andre
      Permalink to comment#

      My bad… Too used to forum code tags.

      For HTML5 ‘placeholder’ method:

      For JS ‘value’ method:

    • Andre
      Permalink to comment#

      What the heck? Ok… Let’s just do it this way: For this JS method just add class=”default-value” to the input tag and leave everything else the way you have it.

    • Unfortunately, this has to work in ie6 as well. Currently I have a span underneath the input field to simulate the functionality. But I don’t want to do it that way.

      The two forms where I’m using this are one input forms. For the submit, would it be possible to throw out the default value using onclick or onsubmit?

  3. Jeff Shamley
    Permalink to comment#

    Perfect! Exactly what I was looking for. Thanks for the snippets.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".