Keep your HTML from Text Input and Textarea Default Values

Posted on 29th Mar, 2012 in jQuery Snippets


Do you want to keep the default values in your text input & textarea from elements when they get out of focus?

The code below will remove the default value if the field is active and then if the user doesn’t input anything and field is out of focus the default value will appear back inside.

To accomplish this we will need to use the jQuery library and all you need to do is copy & paste the code below between your head tags.


<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
  $('.ftxt').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;
        }
    });
  });

  $('.fta').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;
        }
    });
  });
});
</script>

And this a very simple form with text input and textarea fields.


<form method="post" action="#">
    <input type="text" name="t1" id="t1" value="Enter you email address..." maxlength="255" class="ftxt" />
    <textarea class="fta" rows="10" cols="40">Comments / Questions / Suggestions</textarea>
</form>