Skip to content Skip to sidebar Skip to footer

How To Save Items To Cart Using LocalStorage

So I have a table like this:
Book Title Author

Solution 1:

In order to save the data contained in your table's row... Like the book title and author, I suggest you to use some objects contained in an array.

Then you'll have to stringify that prior to use localStorage.

When you'll want to retreive the stored data, you'll have to parse it back to an array of objects.

Sadly, SO snippets do not like the use of localStorage... So my working demo is on CodePen.

Here's the relevant code:

// The "add to cart" handler.
$("table").on("click", ".AddToCart", function(e){

  // Get previous storage, if any.
  var storage = JSON.parse(localStorage.getItem("cart"));
  if(storage==null){
    storage = [];
  }

  var row = $(this).closest("tr");
  var title = row.find("td").eq(0).text().trim();
  var author = row.find("td").eq(1).text().trim();

  // Create an object to store.
  var data = {author:author,title:title};
  storage.push(data);

  // Store it.
  localStorage.setItem("cart",JSON.stringify(storage));
});

Solution 2:

Use classes instead of IDs, and attach the listener using Javascript instead of inline attributes (which is as bad as eval). No need for jQuery. For example:

document.querySelector('table').addEventListener('click', (e) => {
  if (e.target.className !== 'AddToCart') return;
  // e.target refers to the clicked button:
  const [bookTd, authorTd] = [...e.target.closest('tr').children];
  addToLocalStorage({ title: bookTd.textContent, author: authorTd.textContent });
});

function addToLocalStorage(obj) {
  console.log('adding ' + obj);
}
<table border="1">
  <tbody>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
      <th> Book </th>
    </tr>
    <tr>
      <td class="Book_Title">Gone </td>
      <td class="Author">Micheal Grant</td>
      <td><button class="AddToCart">Add To Cart</button> </td>
    </tr>
    <tr>
      <td class="Book_Title">The Knife of never letting go</td>
      <td class="Author">Ryan Howard</td>
      <td><button class="AddToCart">Add To Cart</button> </td>
    </tr>
  </tbody>
</table>

Post a Comment for "How To Save Items To Cart Using LocalStorage"