表单的操作

序列化

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

回填

$.fn.formFieldValues = function (data) {
        var els = this.find(':input').get();

        if (arguments.length === 0) {
            // return all data
            data = {};

            $.each(els, function () {
                if (this.name && !this.disabled && (this.checked
                        || /select|textarea/i.test(this.nodeName)
                        || /text|hidden|password/i.test(this.type))) {
                    if (data[this.name] == undefined) {
                        data[this.name] = [];
                    }
                    data[this.name].push($(this).val());
                }
            });
            return data;
        } else {
            $.each(els, function () {
                if (this.name && data[this.name]) {
                    var names = data[this.name];
                    var $this = $(this);
                    if (Object.prototype.toString.call(names) !== '[object Array]') {
                        names = [names]; //backwards compat to old version of this code
                    }
                    if (this.type == 'checkbox' || this.type == 'radio') {
                        var val = $this.val();
                        var found = false;
                        for (var i = 0; i < names.length; i++) {
                            if (names[i] == val) {
                                found = true;
                                break;
                            }
                        }
                        $this.attr("checked", found);
                    } else {
                        $this.val(names[0]);
                    }
                }
            });
            return this;
        }
    };

发表评论

电子邮件地址不会被公开。 必填项已用*标注