I used a little jQuery last night to clear some form fields. The basic idea was, there were a couple text inputs in the form for first and last name; rather than label the fields, I made the value of each form to be initially “First” and “Last” respectively.
Then I was requested to make it so that when the field was clicked on, the word “First” or “Last” (respectively) would disappear, so that you could then proceed to enter a value without needing to highlight and delete the existing value of the text field.
It turns out that with jQuery, this is simple enough; let’s assume your field has the class “clearme”:
1 2 3 4 5 | $(document).ready(function () { $('.clearme').focus(function() { $(this).val(""); }); }); |
If you’re familiar with jQuery, you know that the wrapper $(document).ready() simply waits until the page is finished loading, then executes the function you’ve passed to it. In this case, the function passed looks for an item of the class “clearme” and waits for that element to receive focus. When it does, it changes the value to “”.
Simple enough… but wait! Now if the user types in “Beauregard Charles Maurice” as a first name, if he inadvertently clicks on the text box again, his name will disappear. He would need to type that all over again. What can be done?
There may be multiple ways; but jQuery has a handy method called “one” which will execute an event one time only, which sounds like just what we want. So we’d change the body of that inner function to look like:
1 2 3 | $('.clearme').one("focus", function() { $(this).val(""); }); |
Voila. That last code could be seen in action here. Have fun.

