How can I locate and modify a particular cell within an HTML table using just JavaScript?

For my project, I am required to develop a functional shopping cart with a remove function. If an item is already in the cart, it should update the existing data when added again.

Let's say I have the following items in my cart:

Name: Quantity: Price: Total: Potato 1 1 1

Using a table to display this cart, if I select another potato from a dropdown list, I want to update the quantity and total of the existing potato in the cart to become 2 and 2 respectively. I've been stuck on this problem for hours now without making any progress towards a solution.

Below is the current code that adds items to the table:

"use strict"; const btn = document.getElementById('toevoegen'); ...

In addition, here is the HTML code as requested:

<!DOCTYPE html> <html lang="nl"> ...

I have implemented a function to check if the selected item from the dropdown list already exists in the table. However, I'm unsure how to target a specific cell within the table to perform this check.

Suppose I choose potato,

I want to verify if there is already an item named potato in my table, and if so, update the quantity and total of that item accordingly.

Is this achievable?

Answer №1

By assigning a unique ID (hopefully) to TR, it becomes easy to verify its existence and update it if it already exists:

"use strict";
const btn = document.getElementById('toevoegen');
const keuzeLijst = document.getElementById('groente');
const aantalArt = document.getElementById('aantal');
leesGroenten();

// Read in the JSON file
async function leesGroenten() {
/* changed */
//    const response = await fetch("groenten.json")
/* start temporary .json */
    const response = {
    ok: true,
    json: async () => {
        return [{
          naam: "name 1",
          prijs: "price 1",
          eenheid : "unit 1"
        },
        {
          naam: "name 2",
          prijs: "price 2",
          eenheid : "unit 2"
        }]
      }
    }
/* end temporary .json */
    if (response.ok) {
        const groenten = await response.json();
        console.log(groenten);
        verwerkGroenten(groenten);
    } else {
        console.log("oops something went wrong!");
    }
};

// Process the JSON file
function verwerkGroenten(groenten) {
    for (const groente of groenten) {
        voegGroentenToeAanLijst(groente);
    }
};

// Add JSON file objects to the vegetable list
function voegGroentenToeAanLijst(groente) {
    let keuzeGroente = document.createElement("option");
    keuzeGroente.dataset.naam = groente.naam;
    keuzeGroente.dataset.prijs = groente.prijs;
    keuzeGroente.dataset.eenheid = groente.eenheid;
    keuzeGroente.dataset.aantal = 1;
    keuzeGroente.innerText = groente.naam + '(' + `${groente.prijs}` + "/" + `${groente.eenheid}` + ')';
    keuzeLijst.appendChild(keuzeGroente);

}

btn.onclick = controleLijst;

function controleLijst() {
    if (aantalArt.value === '' || aantalArt.value < 1) {
        document.getElementById('foutMelding').hidden = false;
    } else {
        document.getElementById('foutMelding').hidden = true;
    const groenteNaam = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam;
    let gevondenListItem = vindListItemMetNaam(groenteNaam);
    if (gevondenListItem === null) {
        voegGroenteToeAanMandje(groenteNaam)
    } else {
        //Not sure how to update cells if not found
        voegGroenteToeAanMandje(groenteNaam)
        updateListItem(gevondenListItem)
    }
}
}
//This function searches the table for an item with the same name as the selected vegetable.
function vindListItemMetNaam(groenteNaam) {
    const groenteNamen = document.querySelectorAll("tr");
    for (const groente of groenteNamen) {
        if (groente.id === groenteNaam) {
            return groente;
        }
    }
    return null;
}
//This function updates an existing item
function updateListItem() {
    console.log("already exists");

}
// After successful validation, the item is added to the table using the following code
function voegGroenteToeAanMandje() {
/* changed */
    const tbody = document.getElementById("tabel");
/* id is set in HTML already */
//    tbody.id = 'tabel'

/* check if TR with this id already exists */
    const exist = document.getElementById(keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam);
/* set tr to already existed row or insert a new one if it doesn't exist */
    const tr = exist || tbody.insertRow();
    tr.id = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam;
/* used to check existence of columns shorter method than alternative: if (exist) ... else ... */
    var child = 0;
/* get existing cell or insert new one */
    const tdNaam = tr.children[child++] || tr.insertCell();
/* do you really need an ID here? */
//    tdNaam.id = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam
    tdNaam.innerText = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam;
    const tdAantal = tr.children[child++] || tr.insertCell();
    tdAantal.innerText = 1;
/* avoid using same IDs on multiple elements */
//    tdAantal.id = 'quantity';
    const tdPrijs = tr.children[child++] || tr.insertCell();
    tdPrijs.innerText = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.prijs;
/* avoid using same IDs on multiple elements */
//    tdPrijs.id = 'price'
    const tdTeBetalen = tr.children[child++] || tr.insertCell();
    tdTeBetalen.innerText = tdPrijs.innerText;
/* avoid using same IDs on multiple elements */
//    tdTeBetalen.id = 'to pay';
/* static cell, no need to update if already exists */
    if (!exist)
    {
      const removeTd = tr.insertCell();
      const removeLink = document.createElement("img");
      removeLink.src = "trashcan.png"
      removeTd.appendChild(removeLink);
      removeLink.onclick = function () {
          const tr = this.parentElement.parentElement;
          tr.remove();
      }
    }
};
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="icon" href="javascript.ico" type="image/x-icon">
  <title>Vegetable Store</title>
  <link rel="icon" href="vegetablestore.ico" type="image/x-icon">
  <link rel="stylesheet" href="vegetablestore.css" />
  <script src="vegetablestore.js" defer></script>
</head>

<body>
  <img src="banner.jpg" id="banner" alt="banner">
  <h1>Order</h1>
  <label>Vegetable:
    <select id="groente">
      <option value="">--- make your choice ---</option>
    </select>
  </label>
  <label>Quantity:
    <input id="aantal">
  </label>
  <button id="toevoegen">Add to Cart</button>
  <button id="test">Test Button</button>
  <table id="tabel">
    <thead>
        <tr>
            <th>Vegetable</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>To Pay</th>
            <th>     </th>
        </tr>
    </thead>
    <tbody>
        
    </tbody>
</table>
<div id="error" hidden class="error">Error! Choose vegetable and quantity (at least 1).</div>

<!-- added start -->
<div id="errorMessage">No clue what this is for</div>
<!-- added end -->

</body>

</html>

I've inserted /* comments */ throughout the code.

P.S. Since you are requesting in English, please provide code in English next time, as it can be difficult to read and understand non-English code.

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

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

Experiencing difficulty navigating JSON objects

I am facing an issue with a JSON structure that has the following format: [ { "coordinates": [ 75.71027043, 26.88661823 ] }, { "coordinates": [ 75.71027043, 26.88661823 ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

Express in Node.js throwing error: 'Cannot GET /'

I recently created a contact us form on my website where users can input their email, name, and gender. The entered data is then stored in an output.txt file. Everything was working fine when I initially developed the website. However, today when I tried t ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...

Having difficulty verifying the elements of an associative array after using json_decode

My goal is to implement form validation in PHP and send any errors to the AJAX call. I have structured the form inputs as an array with named indexes from the AJAX call to the PHP controller. Upon decoding it using json_decode() in PHP, my intention is to ...

Turn off client-side hydration in Nuxt.js or Prevent leaking raw data in Nuxt.js

Working on a Web App built with Nuxt.js for Server-Side Rendering poses some challenges. To safeguard my backend data, I turned to asyncData and Axios for communication with the server. However, Nuxt.js inadvertently exposed my backend data to clients th ...

Reset the input field upon button press

Is there a way to clear the input field after pressing the button? <div class="form-group autocomplete"> <div class="input-group search"> <input id="search" name="searchterm" type="search" class="form-control form-control search-input" pl ...

No files located by the server

My experience with writing a basic express script to serve a webpage with embedded Javascript has been quite frustrating. The server seems to struggle finding the files I provide, and what's even more aggravating is that it sometimes works but then su ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

Image displayed in tooltip when hovering over

I have been experimenting with displaying an image in a tooltip when hovering over it. I came across a fantastic solution that suits my needs: Codepen CSS: @import "compass"; * { box-sizing: border-box; } .tooltip { position: relative; border-bo ...

Exclude files from all folders except one in gulp source

This is the structure of my folders: views | - core | | | -core.module.js | core.controller.js | some.js | - home | -home.module.js home.controller.js somemore.js ... ... In my gulp file, I am looking to include all js files from the views ...

Is the second parameter of the function being used as a condition?

Why is it necessary to validate the helpText argument within the function to be non-equative to null when its ID is linked with the span tag? The functions task is to set and clear help messages in the form field using built-in CSS classes. <input id ...

What causes the translation of text within HTML tags to occur when attempting to retrieve it during Web Scraping?

Exploring the world of web scraping, I am currently immersed in a small project. In this snippet of code, I am capturing the HTML content and storing it in a variable named soup. source=requests.get(URL) soup=BeautifulSoup(source.text,'html.parser&apo ...

How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to ...

Are there any tools available that can generate CSS code automatically

Our team offers a pre-set CSS file along with the HTML mock-up for partners to customize, such as changing colors and background images, to match their desired aesthetic. They then provide feedback on the modified CSS files back to us. However, we face a ...

How can I get rid of the table borders and set colors for every other row in the

How can I remove the border lines from a table and assign colors to alternate rows in the table? Follow this link for the code: https://stackblitz.com/angular/kooxxyvddeqb?file=app%2Ftable-sticky-columns-example.css Thank you in advance ...

determine a distinctive identification for an HTML ID

<div id=Pear1> <div id=Circle></div> </div> <div id=Pear2> <div id=Circle></div> </div> <div id=Pear3> <div id=Circle></div> </div> <div id=Pear4> <div id=Circ ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

What sets apart a .class element from element.class in CSS?

I was browsing through this tutorial http://www.w3schools.com/css/tryit.asp?filename=trycss_nesting and noticed a confusing point. Why did they use .marked p instead of p.marked? When I tried changing it to p.marked, the text didn't turn white as expe ...