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
A big thank you to Barnabas Kendall for his answer, very useful.
However I found 1 error in it regarding restoring radio buttons, where instead of selecting the correct one it just copied the saved value to all buttons in group.
Fortunately it's simple to fix. Just replace
if(this.type == 'checkbox') {
With
if(this.type == 'checkbox' || this.type == 'radio') {
and it will correctly update radio buttons
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);
}
};
To serialize into a string: var s = $('form').first().serialize();
To restore based on that string: $('form').first().deserialize(s);
Of course you'll need a derserialize plugin such as the one I originally posted here.
$.fn.deserialize = function (serializedString)
{
var $form = $(this);
$form[0].reset();
serializedString = serializedString.replace(/\+/g, '%20');
var formFieldArray = serializedString.split("&");
// Loop over all name-value pairs
$.each(formFieldArray, function(i, pair){
var nameValue = pair.split("=");
var name = decodeURIComponent(nameValue[0]);
var value = decodeURIComponent(nameValue[1]);
// Find one or more fields
var $field = $form.find('[name=' + name + ']');
// Checkboxes and Radio types need to be handled differently
if ($field[0].type == "radio" || $field[0].type == "checkbox")
{
var $fieldWithValue = $field.filter('[value="' + value + '"]');
var isFound = ($fieldWithValue.length > 0);
// Special case if the value is not defined; value will be "on"
if (!isFound && value == "on") {
$field.first().prop("checked", true);
} else {
$fieldWithValue.prop("checked", isFound);
}
} else { // input, textarea
$field.val(value);
}
});
return this;
}
More info: https://stackoverflow.com/a/24441276/1766230
Here's a jsfiddle that let's you play around with setting values, clearing, resetting, and "deserializing": http://jsfiddle.net/luken/4VVs3/
checkbox
or radio
isn't set, the value is null
Deactivates checkbox
or radio
if value is null
$.fn.formData = function(values) {
var form = $(this);
var inputs = $(':input', form).get();
var hasNewValues = typeof values == 'object';
if (hasNewValues) {
$.each(inputs, function() {
var input = $(this);
var value = values[this.name];
if (values.hasOwnProperty(this.name)) {
switch (this.type) {
case 'checkbox':
input.prop('checked', value !== null && value);
break;
case 'radio':
if (value === null) {
input.prop('checked', false);
} else if (input.val() == value) {
input.prop("checked", true);
}
break;
default:
input.val(value);
}
}
});
return form;
} else {
values = {};
$.each(inputs, function() {
var input = $(this);
var value;
switch (this.type) {
case 'checkbox':
case 'radio':
value = input.is(':checked') ? input.val() : null;
break;
default:
value = $(this).val();
}
values[this.name] = value;
});
return values;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check out my jQuery Populate plugin:
http://www.keyframesandcode.com/code/development/javascript/jquery-populate-plugin/
Populates all form elements as well as labels and any contained HTML elements.
In case you need to handle this case: <input name="this[is][my][input][]" />
- and you, the greedy guy, need the whole matrix parsed:
To populate:
http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html
To retrieve values:
Use $('form').serialize()
and pass the results to this function:
http://phpjs.org/functions/parse_str/