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
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;
}
See jQuery plugin to serialize a form and also restore/populate the form
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With