У меня есть требование сохранить состояние формы в файле cookie, поэтому этот параметр можно запомнить для данного пользователя. Я использую jQuery, и мой план таков:
Saving:
//generate a param string from the form settings
var paramString = $.param($("#my-form").serializeArray());
//save it to a cookie
$.cookie("my-form-cookie", paramString);
Loading:
//get the cookie value
var savedParams = $.cookie("my-form-cookie")
//turn it into an object with field names as keys and field values as values
var formObject = JSON.parse('{"' + decodeURI(savedParams).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
//go through this, modifying the form
...
Это недостающая часть головоломки на данный момент.
То, что я планировал делать, было чем-то вроде этого (псевдокод, а не js)
for every key/value pair (key,value)
find element(s) with name = key
if there more than one, it probably radio buttons/checkboxes:
- check the one with value = value and uncheck the rest
if there exactly one
- set the value = value
Прежде чем я перейду к записи функции для этого, которая принимает форму id и строку param-style, я думаю, что кто-то другой имеет либо: a) сделал это более тщательным образом, чем я, или b) попробовал это и решило, что это плохая идея, или обречена на провал.
Кто-нибудь получил какой-либо вклад, на a) или b)?
благодарю! Максимум
Вот что я в итоге сделал. Он получил определенные возможности для очистки, но, похоже, работает нормально. Он обрабатывает вложенные параметры и параметры стиля массива. Вы можете добавить класс dont-cookie
для создания элементов, которые вы не хотите устанавливать из файла cookie, когда он использовался для восстановления состояния.
//convert the form state to a params string and save it to a cookie with the
//name form-<form_id>. Note that all form values are saved to
//the cookie, even the ones with .dont-save (these are ignored on load though)
function saveFormStateToCookie(form, cookie){
//jqueryfy the form if it not already
if(typeof(form) != "object")
form = $(form);
if(typeof(cookie) == "undefined")
cookie = formCookieName(form);
//console.log("using cookie name '"+cookie+"'");
var paramString = $.param(form.serializeArray());
//console.log("saving: (unescaped)\n"+unescape(paramString));
$.cookie(cookie, paramString, {path: "/"});
}
function loadFormStateFromCookie(form, cookie){
//jqueryfy form if it not already
if(typeof(form) != "object")
form = $(form);
if(typeof(cookie) == "undefined")
cookie = formCookieName(form);
//console.log("using cookie name '"+cookie+"'");
//get the cookie value
var paramString = $.cookie(cookie);
//console.log("loaded:(unescaped)\n"+unescape(paramString));
//what if it blank, or the cookie doesn't exist?
if(paramString){
//turn it into an object with field names as keys and field values as values
var formObject = QueryStringToHash(paramString);
var elements, checkableElements, matchedElement;
var changedElements = [];
//set all checkboxes and radio buttons in the form to be blank
form.find("[type='radio'], [type='checkbox']").not(".dont-cookie").removeAttr('checked');
//go through this, modifying the form
$.each(formObject, function(name,values){
//note: value can be an array of values or a string. Let make it always an array, to be consistent
if(typeof(values) === "string"){
values = [values];
}
//find all elements matching the name.
elements = form.find("[name='"+name+"']").not(".dont-cookie");
if(elements.size() > 0){
//iterate over values
$.each(values, function(i,value){
//is there a checkbox/radio with this value, which ISN'T in changedElements?
var checkboxes = elements.filter("[type='radio'], [type='checkbox']").filter("[value='"+value+"'], [value='"+value.replace(/\+/g, " ")+"']").filter(function(i){ return changedElements.indexOf($(this)) === -1});
//yes there is - check it and add it to changedElements
if(checkboxes.size() > 0){
$.each(checkboxes, function(j,checkbox){
checkbox = $(checkbox);
checkbox.attr("checked", "checked");
changedElements.push(checkbox);
});
} else {
//THIS IS WIPING OVER ALL THE CHECKBOXES: WE NEED TO JUST DO IT TO NON-CHECKBOXES
//no there isn't: set their val to value, then add them to changedElements
$.each(elements.not("[type='radio'], [type='checkbox']"), function(i, element){
element = $(element);
element.val(value);
changedElements.push(element);
});
}
});
}
});
} else {
//console.log("Couldn't find a cookie matching "+cookie);
}
}