bcarasco
10/5/2016 - 4:25 PM

$.fn.formFieldValues: copy and restore form values from/into an object

$.fn.formFieldValues: copy and restore form values from/into an object

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

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

        $.each(els, function() {
          var name = this.name || this.id;
          
            if (name && !this.disabled && (this.checked
                                                || /select|textarea/i.test(this.nodeName)
                                                || /text|hidden|tel|date|email|password/i.test(this.type))) {
                if(data[name] === undefined){
                    data[name] = [];
                }
                data[name].push($(this).val());
            }
        });
        return data;
    } else {
        $.each(els, function() {
            var name = this.name || this.id;
            if (name && data[name]) {
                var names = data[name];
                var $this = $(this);
                
                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;
    }
};