Preserving Local Storage Data Across DataTable Pages In Javascript

|
| By Webner

When we write data in local storage it is not kept between dataTable pages. It will overwrite the old data with a new one on each page, means your previous data will be lost on a new dataTable page.

The reason is, on each page new values will be set in the local storage variable (or array).

I tried this javaScript function to store local storage on click of each checkbox:

<script>
function setValue(ID,reviewID,me) { 
     if (me.is(':checked')) {
localStorage.setItem("visibleReviews",
JSON.stringify(visibleReviews));          
} 
}
</script>

I have a number of checkboxes on jQuery datatable pages, and I am passing the id, review id (from the database) and the checkbox itself to the setValue() function. I need to keep the local storage between the jQuery datatable pages. You can see from the screenshot below:

Now what we have to do is, check for the existence of visibleReviews array, if it exists, parse that array and assign to a local array else create a new array.

Code Example:

<script>
function setValue(ID,reviewID,me) { 
var visibleReviews = localStorage["visibleReviews"] ?      JSON.parse(localStorage["visibleReviews"]) : [];
// add this above line as the first statement of your function
 if (me.is(':checked')) {
      localStorage.setItem("visibleReviews", JSON.stringify(visibleReviews));  }
}
</script>

So using this code you will find data from all the pages in your code.

Leave a Reply

Your email address will not be published. Required fields are marked *