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.
HTML
<input id="clearField1" type="text" value="First Name" />
<input id="clearField2" type="text value="Email Address" />
CSS
input {
display: block;
margin: 7px auto;
padding: 4px;
width: 200px;
}
JavaScript
// find the elements
$("#clearField1").click(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"));
}
});