3

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);
});

jsFiddle

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

RobinvdA
  • 1,313
  • 2
  • 13
  • 28
  • Acceptable? that's for you to decide. I would have instead used localstorage if the values of the inputs didn't need to be sent to the server. Otherwise, every request to and from the server while those cookies exist will result in passing those cookies back and forth, including images scripts stylesheets. – Kevin B May 19 '14 at 14:32
  • You might be happier doing an `AutoSave()` function that executes every X seconds using `setTimeout`. Creating a cookie on every keyup may result in noticeable typing lag – arserbin3 May 19 '14 at 14:45
  • Maybe i used the wrong words in my question (it's not my native language), but i was looking for answers/suggestions like the one @arserbin3 gave. – RobinvdA May 20 '14 at 07:15
  • Use [Storages](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage) – Alex May 22 '14 at 13:44
  • Localstorage would really be a better alternative. In order not to loose any data on the other hand, you can use "onBeforeUnload" and send all the data in the callback function. This may or may not work depending on browser. As far as I remember does not work on iOS. Increasing the number should not cause any major problem since only a single function will be called at each keypress IMHO. – Ali Naci Erdem May 22 '14 at 14:26

3 Answers3

2

I'd opt for using local storage (see http://www.w3schools.com/html/html5_webstorage.asp), seems more scalable than setting a cookie for each text input. Also, you mention that the values must be set with each keystroke, why not instead keep the value of the current input in memory, and bind a function which commits the value both to the blur event of the input, and also use setTimeout to impose, say, a 1 second delay on saving the value, queuing these timeouts in an array, and clearing outstanding ones on each keyup event, that way you're only writing to the local storage when the user pauses typing, not with every keystroke.

JamieS
  • 307
  • 2
  • 13
  • I like the 1 sec delay thing, but Theodore's solution seems a bit more clean – RobinvdA May 26 '14 at 07:34
  • Depending on cross-browser support for the beforeunload event, you're right, it does seem a cleaner solution. However, unless you already include JQuery and Modernizr for other reasons, the overhead on the network traffic of including 2 extra (and in the case of JQuery, quite large) JS files seems excessive. – JamieS May 26 '14 at 11:03
1

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/

Community
  • 1
  • 1
vorillaz
  • 6,098
  • 2
  • 30
  • 46
  • This is a nice solution! Is there a max string length you can store in localstorage? I think a JSON string can get pretty long. Also, is onbeforeunload available for every browser? – RobinvdA May 26 '14 at 07:32
  • As I could find out, localstorage stands up to 5MB, I am sure it fits your needs. Also you can have a look for onbeforeubload events over here: http://stackoverflow.com/questions/158673/onbeforeunload-support-detection Furthemore I think you can have try to extend the solution adding support for window unbfocus event or even playing around with your back end code. – vorillaz May 26 '14 at 08:26
0

Use jquery-storage for saving the values https://github.com/julien-maurel/jQuery-Storage-API/blob/master/README.md

Its really simple

$.localstorage.set(inputfield, value)

For setting

$.localstorage.get(inputfield)

For retrieving.

Cookies are often abused for this purpose but cookies get sent to the server on every request. So storing a ton of data in cookies is not a good idea.

Localstorage however was designed for this purpose and is a simpe key value storw in the browser.

Please note that it is a html5 feature and will not work in some older browsers

To circumvent this you can use the cookiestorage provided by jquery storage. But then you also need to include the extra dependencies mentionend in the readme.md

Then use it like this:

var store = $.localstoreage || $.cookiestorage:
 store.set(...........
Marco de Jongh
  • 5,270
  • 3
  • 17
  • 29