[jQuery代码集锦]Default Value of Form Field: 表单输入框的默认值

我们常常需要在表单的各种输入框中显示一些默认的提示信息。如图所示:

jQuery插件Form Field Default Value提供了这样的功能。其代码如下

 1 jQuery.fn.DefaultValue = function(text){
 2     return this.each(function(){
 3         //Make sure we're dealing with text-based form fields
 4         if(this.type != 'text' && this.type != 'password' && this.type != 'textarea')
 5             return;
 6         
 7         //Store field reference
 8         var fld_current=this;
 9         
10         //Set value initially if none are specified
11         if(this.value=='') {
12             this.value=text;
13         } else {
14             //Other value exists - ignore
15             return;
16         }
17         
18         //Remove values on focus
19         $(this).focus(function() {
20             if(this.value==text || this.value=='')
21                 this.value='';
22         });
23         
24         //Place values back on blur
25         $(this).blur(function() {
26             if(this.value==text || this.value=='')
27                 this.value=text;
28         });
29         
30         //Capture parent form submission
31         //Remove field values that are still default
32         $(this).parents("form").each(function() {
33             //Bind parent form submit
34             $(this).submit(function() {
35                 if(fld_current.value==text) {
36                     fld_current.value='';
37                 }
38             });
39         });
40     });

41 }; 

 

可以像下面这样使用: 

 1 $(document).ready(function() {

2 //Assign default value to form field #1
3 $("#fname").DefaultValue("Enter your first name..");
4 $("#lname").DefaultValue("Enter your last name..");
5 $("#pass").DefaultValue("MyPassword");
6 $("#desc").DefaultValue("Describe yourself...");
7 });

 

 

posted on 2011-11-05 17:22  静静的三娃  阅读(597)  评论(0)    收藏  举报

导航