Clearing Input Fields on Focus

Clearing input fields that have placeholder text as values when they receive focus. Remembers the default text in case nothing changes.

by Travis Almand

HTML

<input class="clearField" type="text" value="First Name" />
<input class="clearField" type="text" value="Email Address" />

CSS

input {
    display: block;
    margin: 7px auto;
    padding: 4px;
    width: 200px;
}

JavaScript

// find the elements
$(".clearField").each(function() {
    // save the default value
    $(this).data("defaultValue", $(this).val());
}).focus(function() {
    // test if current value matches default value, if it does then blank the value
    if ($(this).val() == $(this).data("defaultValue")) {
        $(this).val("");
    }
}).blur(function() {
    // test if value is empty, if it is then restore default value
    if (!$(this).val()) {
        $(this).val($(this).data("defaultValue"));
    }
});