Having default text that we later removed when retrieving user input is common in today’s website. Many web developer use this to enhance usability of the website, so user know what to type in what field. There is a lot of way to do this, using both focus and blur event. For example, this is the shortest and easiest way that is commonly used:
<input type="text" id="example-field" name="example-field" value="Your name" onfocus="if (this.value=='Your name') this.value=''" onblur="if (this.value=='') this.value='Your name'" />
However, this approach will be a pain when you are managing a lot of input fields. You will need to type the default text three times, which can lead to a trivial typo. Also, since we check againts the default value, we will not be able to accept this value. Here is the solution, by using the simplicity and power of jQuery, this is a clean and a better way to do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
You can see that we define three functions here, one for focus event, one for blur event and the other one to populate the default value. I’ll briefly explain how they work in short.
We add a callback to each fields with function example_populate_field, this function will make use of jQuery.data, which allow us to attach any data to DOM element. We will iterate to each fields, and store the data in “default” key.
Next, we have a focus callback, example_clean_field, this function check whether the field has “hasfocus” class, if it doesn’t then we add the class and clear the field. Note that we use the “hasfocus” class to determine the state of the field, whether it has been cleared or not.
Lastly, we have example_reset_field that we use for blur event. This function will check the current value, when it’s empty, we remove the “hasfocus” class and set the value back to the default.
The usage as shown above is very simple, you just need to select any input or textarea element, and it will work. For example, using this selector below will make this work to all text input and textarea element.
$('input[type=text], textarea') .focus(example_clean_field) .blur(example_reset_field) .each(example_populate_field);
That’s all. It’s simple, clean and it looks like the most elegant solution I can find. 🙂
Hope that will be useful for you as well. Enjoy.
No comment yet