Store text in a table format in your local storage

I need help figuring out how to save product and price information to local storage when an "add to cart" button is pressed. Can someone provide guidance on how to do this?

Here is the code I currently have:

body>
        
<!--     Header-->
     <div id="header"> 
      <button type="button" class="button">Basket</button>
     </div>

<!--     CSV FILE DATA WILL APPEAR HERE-->
  <div class="container">
   <div class="table-responsive">
    <div id="order_list" onload="appendRow()"><p id="tableintro"> Choose your desired supermarket</p>
    </div>
   </div>
  </div>    
     
<!--THIS BUTTON WILL LOAD DATA FROM CSV FILE-->
<div id="sidebar">
         <div align="center">
 <button type="button" name="load_data" id="load_tesco" class="btn btn-info">Tesco Brent Cross</button>
    </div>
     <div align="center">
         
<!--     Saving to local storage - dont work   -->
 <script>
       function SaveItem() {
       var name = document.parentNode.value;
    var data = document.parentNode.value;
    localStorage.setItem(name, data);
}
     </script>

 <script>
$(document).ready(function(){
 $('#load_tesco').click(function(){
  $.ajax({
   url:"Tesco.csv",
   dataType:"text",
   success:function(data)
   {
    var tesco_data = data.split(/\r?\n|\r/);
    var table_data = '<table class="table table-bordered table-striped">';
    for(var count = 0; count<tesco_data.length; count++)
    {
     var cell_data = tesco_data[count].split(",");
     table_data += '<tr>';
     for(var cell_count=0; cell_count<cell_data.length; cell_count++)
     {  
      if(count === 0)
      {
       table_data += '<th>'+cell_data[cell_count]+'</th>';
      }
      else
      {
       table_data += '<div class="12at"><td>'+cell_data[cell_count]+'</td></div>';
      }
     }
     table_data += '<td id="lastrow"><button onclick="SaveItem()">Add</button class="addb"></td>';
    }
    table_data += '</table>';
    $('#order_list').html(table_data);
   }
  });
 });
 
});
</script>

Answer №1

Pass the data from the cell as a parameter to your SaveItem function (ensure it is passed as a string)

Within the saveItem function, perform the following check: - Check if the key 'basket' exists in the local storage - If it does, append the value of the selected row with a '|' separator - If not, add a new entry

function SaveItem(cell_data) {
      let basket = window.localStorage.getItem('basket');
      if ( basket ) {
        basket += `|${cell_data}`;
      } else {
        basket = cell_data;
      }
      window.localStorage.setItem('basket', basket);
}

for(var count = 0; count<tesco_data.length; count++) {
        var _cellData = tesco_data[count]; 
        var cell_data = _cellData.split(",");
        table_data += '<tr>';
        for(let cell_count=0; cell_count<cell_data.length; cell_count++) {  
            if(count === 0) {
                table_data += '<th>'+cell_data[cell_count]+'</th>';
            } else {
                table_data += '<div class="12at"><td>'+cell_data[cell_count]+'</td></div>';
            }
        }
        table_data += `<td id="lastrow"><button onclick="SaveItem('${_cellData }')">Add</button class="addb"></td>`;
    }
    table_data += '</table>';
    $('#order_list').html(table_data);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP and AJAX to fetch information from a database

I've been attempting to retrieve data from a database using AJAX, but I haven't had any luck so far. Here are the codes I've been working with. I've checked the console for errors, but nothing seems out of the ordinary. HTML: <butt ...

Automating radio button selection in AngularJS: Let your code choose the option

In a form with two radio buttons, I am trying to set the first one as the default selection. <input type="radio" name="playlist" ng-value="myCtrl.cleanPlaylist" ng-model="myCtrl.playlistSelected"> Clean <input type="radio" name="playlist" ng-val ...

Utilizing MEAN.js for uploading images

Following a tutorial on the MEAN stack, I am looking to implement an image upload feature using MongoDB on a server. Resources: Angular directive for file uploads create-spot.client.view.html <div data-ng-controller="SpotsCreateController"> &l ...

Utilizing jQuery to Enable Multi-Checkbox Selection

Looking for the simplest way to obtain the selected checkboxes. This is my script: $(document).ready(function() { $("input[name='chkTextEffects']").change(function() { if ($("#cbSolid").is(':checked') == true) { ...

Internet Explorer is failing to render SVG as content within a pseudo element such as :before or :after

Looking to tackle an issue that stems from the following discussion: Is there a way to use SVG as content in a pseudo element :before or :after. I'm attempting to add a svg triangle after a div using a pseudo-class. div{ background-color: black; w ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Use JSON data to populate a dynamic bar chart in Highcharts

As a beginner in parsing JSON objects to highcharts, I am trying to create a basic bar graph. I have managed to set up the title of the graph, but I am having trouble displaying the series that I want to show (count as series and qpAnswer as xAxis). Below ...

Select the M3 element in a ul using CSS targeting

I am working with a ul containing some li elements, here is an example: <ul class="M199 WIDTHBOX1 5ColumnBox"> <li class="M2"> <a class="M2" href="about-1561.aspx" target="">About</a> <div class="WIDTHBOX2" s ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

What is the best way to retrieve the src value from the class contained in the attribute?

.setAttribute('src', 'http://example.com/'); I am trying to extract a URL from the anchor tag with the class of a.myLink... similar to this example: .setAttribute('href', ''); <a href="http://example.com/" cla ...

Unable to integrate Tailwind CSS in project

Having a bit of trouble with my HTML using Tailwind post CSS. Even though I have installed all necessary packages and linked the CSS, the classes don't seem to be applying. Here is a snippet from the tailwindconfig.js file: module.exports = { conte ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Issues with locating the fonts: React-slick paired with nextjs

Incorporating react-slick into a NextJs project has been quite seamless, however, I'm encountering issues with importing the necessary fonts from the CSS files. To address this snag, I've attempted the following steps: npm install slick-carouse ...

Performing height calculations in JavaScript is necessary to recalculate them whenever there is a

A JavaScript function is used to calculate the height of an iframe element and the document height, then determine if the iframe is on or off based on its height and display properties. The issue arises when changing pages— if the height is less than the ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

What is the best way to broadcast video content from Google Cloud Storage to iOS Safari?

Currently seeking a reliable method to serve videos through Google Cloud Storage that is compatible with all browsers, including Apple devices. I am facing challenges trying to play videos on my website (Vue front end, node.js backend) that are stored in ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

What could be the reason for my typeahead.js not showing the dropdown menu during an ajax request?

I am currently experiencing an issue with the typeahead.js autocomplete in my Laravel application when using AJAX as the data source. The suggestion menu does not display when using AJAX, but it works perfectly fine when the data is retrieved from a div co ...

Guide on utilizing VueJS plugins in the browser without any added layers

I have decided to incorporate VueJS into an old system instead of using JQuery. However, I am facing difficulties in utilizing plugins like I would with JQuery. For instance, when trying to import the "vuetable" library directly into my HTML using script t ...