I'm working on a legacy web app, that's using JQuery.
There's a place where we're trying to save all of the form data to local storage, before we redirect to a different page, so that we can restore it when we return.
This pattern is working on a number of pages:
$(document).ready(function () {
var searchForm = $('form.full-investigation');
var searchFormElements = searchForm.find(':input');
var saveSearchElements = function saveSearchElements() {
var saveData = [];
searchFormElements.each(function(index, element) {
var item = $(element);
var name = element.name;
var value = item.val();
var type = element.type;
var add = true;
if (type === "checkbox") {
value = element.checked;
} else if (type === "radio") {
if (!element.checked) {
add = false;
}
}
if (add) {
saveData.push({ name: name, value: value });
}
});
var serialized = JSON.stringify(saveData);
sessionStorage.setItem('FullInvestigation_criteria', serialized);
};
var loadSearchElements = function loadSearchElements(serializedForm) {
var foundOne = false;
if (serializedForm) {
var saveData = JSON.parse(serializedForm);
for (var i = 0; i < saveData.length; i++) {
var key = saveData[i].name;
var value = saveData[i].value;
try {
var element = searchForm.find(':input[name=' + key + ']');
if (element.length > 1) {
for (var j = 0; j < element.length; j++) {
var each = element[j];
var type = each.type;
if (type === 'radio' && each.value === value) {
each.checked = true;
foundOne = true;
}
}
} else {
element.val(value);
if (value)
foundOne = true;
}
} catch (e) {
var msg = e;
}
}
}
return foundOne;
};
$("#redirectbutton").on('click',
function(event) {
try {
saveSearchElements();
} catch (e) {
}
});
var fullInvestigation_criteria = sessionStorage.getItem('FullInvestigation_criteria');
loadSearchElements(fullInvesigation_criteria);
sessionStorage.setItem('FullInvesigation_criteria', '{}');
});
As I said, this is working on a number of pages.
But when I try to use it on a different page, where it had not been used before, I'm getting syntax errors. The problem is that on this new page, saveSearchElements() encounters :input elements with dotted names. E.g., ticketAndMarking.actualnearinter. So we're saving name/value pair with a key of "ticketAndMarking.actualnearinter"
So when we process that key in And then when we call loadSearchElements, and it processes that key, the line: var element = searchForm.find(':input[name=' + key + ']'); throws an exception with the message: Syntax error, unrecognized expression: :input[name=ticketAndMarking.actualnearinter]