Let's say i have some textboxes/textareas of which the values have to be stored. The values have to be stored on key press, so that no data is lost when the user closes the page too early. Here's my current code (using cookies):
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = '; expires=' + date.toGMTString();
} else var expires = '';
document.cookie = name + '=' + value + expires + '; path=/';
}
$('input').keyup(function () {
var $this = $(this);
createCookie($this.attr('name'), $this.val(), 1);
});
This works great.
With just 4 textboxes i see no problems but imagine having 50+ textboxes or textareas (not accounting usability/user experience). Will this cause any problems?
I'm open to any suggestions/alternatives
As Jamie suggested local storage is a really good approach, cookies could be used as a fallback if Local Storage is not supported.
On the snippet you have provided you have binded the cookie rewrite process in the keyup event, in order to avoid any data loss. I have implemented a more neat solution , when the user unloads the window I have tried to serialise the form data and store it.
//save data generic function
function saveData() {
var dataObj = JSON.stringify($("input,textarea").serializeObject());
if (!Modernizr.localstorage) {
saveToLocalStorage(dataObj);
} else {
createCookie("jsonobj", dataObj, 1);
}
}
Modernizr is used to detect when local storage is available. Furthermore , I have found that using separate cookies for each field is an overkill, I have used a single JSON string instead.
Full jsFiddele example: http://jsfiddle.net/ARUM9/5/
Further reading:
Local storage :Storing Objects in HTML5 localStorage
Local storage browser support: http://caniuse.com/#search=localstorage
Using JSON serialisation : Serializing to JSON in jQuery
Modernizr documentation: http://modernizr.com/docs/