在表单中设置默认值

Monday, August 23, 2010

用google大仙搜索了一把 , 找到了Form Field Default Value这篇博客, 作者写了一个jquery插件,代码如下

jQuery.fn.DefaultValue = function(text) {
return this.each(function() {
    $(this).attr("autocomplete", "off");
    //Make sure we're dealing with text-based form fields
    if (this.type != 'text' && this.type != 'password' && this.type != 'textarea') {
        return;
    }

    //Store field reference
    var fld_current = this;

    //Set value initially if none are specified
    if (this.value == '') {
        this.value = text;
    } else {
        //Other value exists - ignore
        return;
    }

    //Remove values on focus
    $(this).focus(function() {
        if (this.value == text || this.value == '')
        this.value = '';
    });

    //Place values back on blur
    $(this).blur(function() {
        if (this.value == text || this.value == '')
        this.value = text;
    });

    //Capture parent form submission
    //Remove field values that are still default
    $(this).parents("form").each(function() {
        //Bind parent form submit
        $(this).submit(function() {
            if (fld_current.value == text) {
                fld_current.value = '';
            }
        });
    });
});
};

作者的插件中没有做对autocomplete属性的关闭,miclle加上了$(this).attr("autocomplete", "off"); 这一行修复了这个问题!
使用例子:

$(“#myfield”).DefaultValue(“My Default Value..”);

======================华丽丽的分隔线======================
后来, miclle把这插件改了一下, 变得更完美了

jQuery.fn.DefaultValue = function(){
return this.each(function(){
    var flied=this, value=this.value=this.title;
    $(this).focus(function(){
        (flied.value==value||flied.value=='')?flied.value='':''
        }).blur(function(){
        (flied.value==value||flied.value=='')?flied.value=value:''
        }).parents("form").each(function(){
        $(this).submit(function(){
            (flied.value==value)?flied.value='':''
            });
    });
});
};

这样的话,使用的时候只要在标签中加个title属性就ok了
例如

<input type="text" title="title is default value" />
<textarea title="title is default value" ></textarea>
$("input:text, textarea").DefaultValue();

Demo

This entry was tagged jQuery

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top