jQuery - can I fill form inputs from a serialized form string?
-
22-01-2021 - |
문제
Given that I have some form on a page, I know I can get a unicode serialized string using
var query = jQuery('#some-form').serialize();
It's also possible setting the value of each input with $('#some-input').val(...)
. Assuming that same form above was reset, but I still have the query string - is there a simple way to populate the form from that string? I realize I could parse it and set every input/select individually, but I was looking for a simpler solution. Thanks.
해결책
You could serialize the form into a JSON array and use an MVVM mapping plugin like Knockout.js to auto-fill the form.
다른 팁
jquery.deserialize plugin should help you.
If your form only contains text inputs (not as arrays), you may try this plugin, which I've adapted from its unserialize function counterpart (https://gist.github.com/rcmachado/242617#file-jquery-unserialize-js), but instead of returning an object, it fills the form it applies to.
(function($){
$.fn.fillformwithserialized = function(serializedString) {
var str = decodeURI(serializedString);
var pairs = str.split('&');
var p, idx, val;
for (var i=0, n=pairs.length; i < n; i++) {
p = pairs[i].split('=');
idx = p[0];
var txtBox = this.find('#' + idx + ':input');
if (txtBox.is(":text")) {
txtBox.val(p[1]);
}
}
return this;
};
})(jQuery);
Example of use:
var dataSerialised = sessionStorage.getItem('frmVeryImportantStuff');
if (dataSerialised == null || !confirm("We could restore the previous version of the form you posted. Shall we?"))
return false;
else {
$("#frmVeryImportantStuff").fillformwithserialized(dataSerialised);
}
Obviously you'll need to have saved your form in the sessionStorage in the first place. Example:
sessionStorage.setItem("frmVeryImportantStuff", $(frmVeryImportantStuff).serialize());