How to save jQuery cloned text input to cookie or html5 storage?

339 views Asked by At

I have a text input and when user is click on button the jQuery clone input and make another one.

$(document).ready(function(){
$('.add').click(function(event){
    var predmet = $('input.clear:last');
    $('div.clear').before(predmet.clone().val('').slideToggle( "fast" ));
    $('div.clear').before(predmet.next().clone().val(0));
    event.preventDefault();
});

Now, my question is - How i can save input forms to cookie or html5 storage (what is better solution?). I want when is page refresh to appear cloned text input ,who have previously saved with cookie or html5. Thanks!

2

There are 2 answers

9
charlietfl On BEST ANSWER

You can create an array of objects that can be saved to localStorage using JSON.stringify() during save, and JSON.parse() during retrieval to return string to array.

What you save will depend a bit on your UI needs.

The very simplest format of this array can be easily obtained using jQuery serializeArray(). If you need more detail like label value, display settings etc you would need to create your own objects for the array

Thus you could do:

var data = $('#formID').serializeArray();
localStorage.setItem('myFormData', JSON.stringify( data));

Then on page load, retrieve string from localStorage, return it to array using JSON.parse and loop over array to create your fields

jQUery serializeArray() Docs

0
Captain John On

html5 storage is a good choice if your user base is likely to have HTML storage available. Cookie storage is better if you have to support old browsers.