Handling Pre-populated Form Fields

I’m working on something right now where I needed a quick and dirty way to make form fields go blank when a user clicks on them and then re-populate if they don’t enter any text.

I know this is standard behavior right now, but I’ve always had a personal javascript library that I use to handle these sort of interactions. However, in this case, I can’t use it. So here’s my snippet for the day.

$('input[type=text]').focus(function() {
                        var val = $(this).attr('value');
                        
                        $(this).attr('value', '');
                        
                        $(this).blur(function() {
                            if($(this).val() == '') {
                                $(this).attr('value', val);
                            }
                            
                        });
                        
                    });

It just listens for a user’s click on a form field and stores the value, then sets the value to be blank. It also sets up another event in which the user “blur’s” or clicks on something else on the page. In this case, it checks to see if the user has entered anything. If they haven’t we set the form field value to it’s original.

NOTE: this requires the jQuery library.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.