Setting default text on form fields helps to instruct users on what needs to be entered into the fields. Many Web designers use the default text as form input labels to help save space or change up the design of the forms. You can set a default value using the value attribute, but the problem is that if a user clicks into the field, they need to delete what is currently there. The Laithwaites Wine Web site (www.laithwaiteswine.com) has a simple implementation of this: their e-mail newsletter signup field at the bottom left corner of the Web page.
The following script allows you to set default text in a field. If a user clicks into that field, the default text disappears and the user can then enter their own text. If the user doesn't enter any text and then clicks or tabs out of the input field, the default text is added back in. The script uses the focus and blur events to achieve this eff ect and an example of the script in action.
1. Set up the HTML form input element that should contain the default text:
<input type="text" id="email-input" value="Search"/>
2. Create a variable to hold the value of the default text that will be displayed in the field:
var defaultText = "Search";
3. Select the #email-input element and attach a focus event:
$("#email-input").bind('focus', function(){
});
4. Within the focus event handler function, add an if statement that tests whether the selected input (this) contains any value. If no value is detected, set the value to defaultText. If a value is detected, remove it. Regardless of whether a value exists, the color of the text changes to #333 (dark gray).
$("#email-input").bind('focus', function(){
if ($(this).val() == defaultText) {
$(this).val('');
}
$(this).css('color', '#333')
});
5. Next, set up a blur event to fire when the #email-input element loses focus.
$("#email-input").bind('blur', function(){
});
6. Within the blur event handler function, add a similar if statement that tests whether the selected input (this) contains any value. If no value is detected, set the value to defaultText. Also, change the color of the text to #333.
$("#email-input").bind('blur', function(){
if ($(this).val() == '') {
$(this).val(defaultText)
}
$(this).css('color', '#333')
});
0 comments:
Post a Comment