0

I am making a HTML form where I need my users to be able to get back whatever data that they have filled up, after closing the window/tab and reopening it.

If I do it with JavaScript cookies or HTML 5 local storage, Then I will have to write code for every single input tag there is, even if its like thousands.

So, what would be the most efficient way to accomplish this?

P.S. I am using PHP for back end processing.

I want the function just like we have in the browser like restoring the session in firefox or chrome.

Aman Kumar
  • 123
  • 8

2 Answers2

6

you can use like this with localstorage.

localStorage.setItem('formData', JSON.stringify($('form').serialize())); //comfortable java script way.

or with cookies you can like this

$.cookie('formData', JSON.stringify($('form').serialize())); //can support old browsers also.

please read the excellent accepted answer at storage-vs-cookies you will know which one to use.

Community
  • 1
  • 1
Raghavendra
  • 3,530
  • 1
  • 17
  • 18
2

LocalStorage is your best option.

I will have to write code for every single input tag there is, even if it's like thousands.

That is not true. You can use a JS loop, or a jQuery each, to do that:

$("input").each(function(){
              $(this).val(storage.getItem($(this).attr("id")));
          })
          .change(function(){
              storage.setItem($(this).attr("id"), $(this).val());
          });

When the page loads, you loop through each input on the page and put content into it based on the input's ID.Then you attach an event listener to all the inputs, which saves any changes into local storage.

I have not tested this, and it is only for illustrations purposes. This code probably won't work straight away, but I hope you understand the concept.

Reuven Karasik
  • 475
  • 5
  • 14