Skip to content

Instantly share code, notes, and snippets.

@siffring
Created February 4, 2010 20:41
Show Gist options
  • Save siffring/295080 to your computer and use it in GitHub Desktop.
Save siffring/295080 to your computer and use it in GitHub Desktop.
// Save Form Field Prompts (jQuery)
//
// If you have form fields with default values like "Enter search term"
// this code will save that value, hide it when a user focuses on the field
// and restores it when they leave the field if they didn't enter anything.
// Select the fields you want to save
var $fields = $(".commentform textarea, .commentform input.text");
// No need to change anything below here
$fields.each(function(){
$(this)
.data("val",$(this).val()) // save the initial value
.focus(function(){
$(this).val(''); // clear the field on focus
})
.blur(function(){
// reset the field to the original value if the user didn't input anything
if ($(this).val()=='') {
$(this).val($(this).data("val"));
}
});
});
@jtallant
Copy link

Awesome. One thing I noticed is that if the user clicks the field (even after editing it from the original value) it sets the value to empty. It would force the user to retype a whole field if they attempt to change a field or fix a simple typo. This version fixes that.

$fields.each(function(){
    $(this)
        // save the initial value
        .data("val",$(this).val())

        // clear the value only if it has not been modified
        .focus(function(){
            if ($(this).val() == $(this).data("val")) {
                $(this).val("");
            }
        })

        // reset the field to the original value if the user didn't input anything
        .blur(function(){
            if ($(this).val() === '') {
                $(this).val($(this).data("val"));
            }
        });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment