Opposite to serializeArray in jQuery (restore form)

旧城冷巷雨未停 提交于 2020-02-13 08:38:11

问题


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

回答1:


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




回答2:


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);
}



回答3:


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;
}



回答4:


The opposite to serializeArray is .param()

In fact, the serialize function does a serializeArray first, and then applies param()

serialize: function() {
    return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
...


来源:https://stackoverflow.com/questions/9370449/opposite-to-serializearray-in-jquery-restore-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!