Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite to serializeArray in jQuery (restore form)

Having the data from serializeArray, how do you update the form with it?

var values = form.serializeArray();
form.deserializeArray(value); // What is the deserializeArray analogue?
form.seriaizeArray() === values; // So that this is always true
like image 224
Dmytrii Nagirniak Avatar asked Feb 21 '12 00:02

Dmytrii Nagirniak


3 Answers

This work for me

// By Jorhel Reyes
jQuery.fn.deserializeArray = function (ObjectSerialized, isJson) 
{
    var $form = jQuery(this);
    var json = {};
        jQuery.each(ObjectSerialized, function(i, pair){
            var name = decodeURIComponent(pair.name).split("[");
            if( typeof name[1] != "undefined" ){
                if( typeof json[name[0]] === "undefined"){ json[name[0]] = []; }
                json[name[0]].push(decodeURIComponent(pair.value));
            }else{
                json[name[0]] = decodeURIComponent(pair.value);
            }
        });
    var asignValue = function(element, val){
        if( !element.length ){ return; }
        if (element[0].type == "radio" || element[0].type == "checkbox") {
            var $fieldWithValue = element.filter('[value="' + val + '"]');
            var isFound = ($fieldWithValue.length > 0);
            // Special case if the value is not defined; value will be "on"
            if (!isFound && val == "on") {
                element.first().prop("checked", true);
            } else {
                $fieldWithValue.prop("checked", isFound);
            } 
        } else { // input, textarea
            element.val(val);
        }
    };
    jQuery.each(json, function(name, value){
        var element = '';
        if( typeof value === "object" ){
            element = $form.find('[name="' + name + '[]"]');
            jQuery.each(value, function(k, val){
                var elm = jQuery( element[k] );
                asignValue(elm, val);
            });
        }else{
            asignValue($form.find('[name="' + name + '"]'), value);
        }
    });
    return this;
}
like image 186
Jorhel Reyes Avatar answered Oct 17 '22 03:10

Jorhel Reyes


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

like image 4
Pavel Chuchuva Avatar answered Oct 17 '22 04:10

Pavel Chuchuva


We can iterate over the array and restore the form.

for (var i = 0; i < values.length; i++) {
    $("input[name='" + values[i].name + "'], select[name='" + values[i].name + "']").val(values[i].value);
}
like image 4
Kaushik Avatar answered Oct 17 '22 02:10

Kaushik