1(function ($) { 2 function formsaver(method, container) { 3 function getStorageId(container) { 4 return 'formdata__$url__$extra'.replace('$url', location.pathname) 5 .replace('$extra', container.attr('id') || ''); 6 } 7 8 var storageId = getStorageId(container), 9 controller = { 10 save: function () { 11 this._save(storageId, this.extractValues()); 12 }, 13 restore: function () { 14 this.fillFields(this._load(storageId)); 15 }, 16 clear: function () { 17 this._remove(storageId); 18 }, 19 20 extractValues: function () { 21 var formData = container.find(":input[name]").serializeArray(), 22 preparedData = {}; 23 $.each(formData, function (index, element) { 24 var name = element.name, 25 value = encodeURIComponent(element.value); 26 if (preparedData[name]) { 27 preparedData[name] = preparedData[name] instanceof Array ? 28 preparedData[name].concat(value) : 29 [preparedData[name], value]; 30 } else { 31 preparedData[name] = value; 32 } 33 }); 34 return preparedData; 35 }, 36 fillFields: function (formData) { 37 // uncheck all checkboxes first, because they would not be in the formData array. 38 function isEmpty(obj) { 39 for(var key in obj) { 40 if(obj.hasOwnProperty(key)) 41 return false; 42 } 43 return true; 44 } 45 46 if(formData && !isEmpty(formData)) { 47 container.find("[type=checkbox]").prop('checked', false); 48 } 49 50 $.each(formData, function (name, value) { 51 var field = container.find("[name=" + name + "]"), 52 inputType = field.prop('type'); 53 value = value instanceof Array ? value.map(decodeURIComponent) : 54 decodeURIComponent(value); 55 if (inputType === 'checkbox') { 56 field.filter("[value=" + value + "]").prop('checked', true); 57 } else if (inputType === 'radio') { 58 field.filter("[value=" + value + "]").prop('checked', true); 59 } else { 60 field.val(value); 61 } 62 63 field.trigger('change'); 64 }); 65 }, 66 67 _save: function (storageId, data) { 68 localStorage.setItem(storageId, JSON.stringify(data)); 69 }, 70 _load: function (storageId) { 71 return localStorage.getItem(storageId) ? JSON.parse(localStorage.getItem(storageId)) : {}; 72 }, 73 _remove: function (storageId) { 74 localStorage.removeItem(storageId); 75 } 76 }, 77 methodsQueue = method instanceof Array ? method : [method]; 78 79 $.each(methodsQueue, function (index, method) { 80 controller[method](); 81 }); 82 } 83 $.fn.saveForm = function () { 84 formsaver('save', $(this)); 85 }; 86 $.fn.restoreForm = function () { 87 formsaver(['restore', 'clear'], $(this)); 88 }; 89})(jQuery);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.