jQuery plugin to serialize a form and also restore/populate the form?

前端 未结 8 2063
花落未央
花落未央 2020-12-02 08:40

Is there a jQuery plugin out there that can serialize a form, and then later restore/populate the form given the serialized value? I know the form plugin can serialize as a

8条回答
  •  温柔的废话
    2020-12-02 09:02

    Here's a little something I rolled based on work of others, specifically serializeAnything:

    /* jQuery.values: get or set all of the name/value pairs from child input controls   
     * @argument data {array} If included, will populate all child controls.
     * @returns element if data was provided, or array of values if not
    */
    
    $.fn.values = function(data) {
        var els = $(this).find(':input').get();
    
        if(typeof data != 'object') {
            // 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))) {
                    data[this.name] = $(this).val();
                }
            });
            return data;
        } else {
            $.each(els, function() {
                if (this.name && data[this.name]) {
                    if(this.type == 'checkbox' || this.type == 'radio') {
                        $(this).attr("checked", (data[this.name] == $(this).val()));
                    } else {
                        $(this).val(data[this.name]);
                    }
                }
            });
            return $(this);
        }
    };
    

提交回复
热议问题