An error pops up on the console every time I attempt to modify the quantity of items in the shopping

I'm having trouble with my shopping cart code in JavaScript. When I try to log the variables priceElement and quantityElement in the console, nothing shows up even though the tutorial says it should. Additionally, I'm getting an error message 'dairyItemsContainer.getElementById is not a function' when trying to remove an item from the cart. I need assistance with getting the total, price, and remove buttons to stay in sync so that when an item is removed, the total updates accordingly. Can anyone provide guidance?

Check out the HTML for the shopping cart below:

<div>
<table>

  <thead>
    <tr>
      <th>Items</th>
      <th>Price</th>
      <th>Quantity</th>
      <th></th> <!--- remove --->
      <th>Total</th>
    </tr>
  </thead>

  <tbody>

    <tr>
      <td>Brown Sugar</td>
      <td id='price'>€1.59</td>
      <td class='quantity'><input class="quantity" name="quantity[]" type="text" value="2"></td>
      <td><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
    </tr>

    <tr>
      <td>Soda Bread</td>
      <td id='price'>€2.99</td>
      <td class='quantity'><input class="quantity" name="quantity[]" type="text" value="1"></td>
      <td><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
    </tr>

    <tr>
      <td>Milk</td>
      <td id='price'>€0.99</td>
      <td class='quantity'><input class="quantity" name="quantity[]" type="text" value="2"></td>
      <td style='float: left;'><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
    </tr>

    <tr>
      <td></td>
      <td></td>
      <td class='totalFont'>Total</td>
      <td class='total'>€5.57</td>
    </tr>

  </tbody>
</table>

Below is the JavaScript code for handling the shopping cart:

var removeCartItems = document.getElementsByClassName("buttonRemoved");
console.log(removeCartItems);
for (var i = 0; i < removeCartItems.length; i++) {
  var button = removeCartItems[i];
  button.addEventListener("click", function (event) {
    var buttonClicked = event.target;
    buttonClicked.parentElement.parentElement.remove();
    updateTotal();
  });
}

function updateTotal() {
  var dairyItemsContainer = document.getElementsByClassName("dairyItems")[0];
  var cartRows = dairyItemsContainer.getElementById("dairyTotalHelp");
  for (var i = 0; i < cartRows.length; i++) {
    var cartRow = cartRows[i];
    var priceElement = cartRow.getElementsByClassName("price")[0];
    var quantityElement = cartRow.getElementsByClassName("quantity")[0];
    console.log(priceElement, quantityElement);
  }
}

Answer №1

Instead of document.getElementById(), you can use

With this change the error will be fixed

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

Looking to crop a canvas without changing its dimensions using jQuery

I'm currently working on a project that involves overlaying two images; one uploaded by the user and the other a default image. However, I am facing an issue when the uploaded image is a rectangle instead of a square, causing the canvas to resize it. ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Tips for capturing the datePicker closing event

Currently, I have successfully implemented a date picker on my website. In some sections of my page, there is a requirement for calculating values based on the start and end dates selected by the user. However, I am facing an issue where I am unable to per ...

CSS trick for stylish arrow placement on top of a slide

Hey there! This is my first time navigating through the slick carousel functionality. I'm currently facing a challenge with adjusting the positioning of the arrow within the slider. My goal is to have the arrow displayed at the top level just like the ...

Continuous dragging with HammerJS (dragging even after releasing)

Is it possible to implement dragging after release using HammerJS (and if so, how)? I am using it in conjunction with AngularJS, but that detail should not be relevant. I'm inquiring about this because I aim to achieve a seamless scrolling experience ...

What techniques does Google use to craft mobile-friendly fixed backgrounds and parallax content within iframes?

Currently, I am working on a test that involves utilizing an intersectionobserver in conjunction with iframe postMessage to adjust the background image in a translate3d manner within the iframe. However, this method is causing significant jitter and potent ...

Steps for organizing values based on the selected value from the dropdown menu in a select option

I have two drop down menus, defined as follows: <select name="" id="district" onchange="selectbyDistrict()"> <option value="one">1</option> <option value="two">2</option> <option value="three">3</option&g ...

Vue.js error: Unable to locate requested resources

Recently, I've been encountering a curious issue when trying to access a specific component in my application. When I manually type the URL http://localhost:8080/detailed-support/start into the browser, the content loads without error. However, none o ...

Certain issues arise when adjusting the padding within the background color of solely the inline text element

Appreciate your time. I'm working on adding background color to the TEXT exclusively, and have successfully done so by styling .post-title { text-transform:capitalize; margin-top:4px; margin-bottom:1px; font-size:22px; background-color:#FFF; dis ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...

What could be causing the error.status value to not be displayed on my Embedded Javascript (EJS) page?

Currently utilizing ejs, node.js & express along with other packages I'm facing an issue where the error.status and error.stack values are not appearing on the rendered page. I suspect that the error variable may be undefined or inaccessible within t ...

Is it possible to adjust the left property following the concealment of an element with JQuery?

My goal is to move an image element using the 'left' property after hiding a div. To achieve this, I am using JQuery's '.promise()' function. Here is my code: HTML code: <div id="outerContainer"> <div id=" ...

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

Overwriting values in a JavaScript array

Within my function, I am running the code snippet below: stores = []; console.log('in stores d.length is ', districts.length); districts.forEach( function ( dis ) { dis.store.forEach( function( store ) { store.structure = dis.structu ...

Positioning an image at the bottom left of the page using absolute positioning is simply not effective

Can anyone help me figure out how to make an image stay just above the footer on the bottom left-hand side of the main content? I've tried using floats, margins, and positioning on left nav elements without success. Here's a link to see what I me ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

Using loops in Sass mixins causes errors

I have been developing a SASS code to generate CSS output that has the following format. background: -webkit-linear-gradient(top, 50%); background: -moz-linear-gradient(top, 50%); background: linear-gradient(top, 50%); This is the SASS mixin code I cr ...

Ensure that this regular expression is able to accurately match all numbers, even those without decimal points

Seeking help to create a script that can extract the negative percentage value between two numbers. One of the numbers is dynamic and includes different currencies, decimals, etc., so I believe a regex is needed for this task. The current script works, but ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

How to align content within a FormControlLabel using Material UI

My goal is to line up the label and radio button inside a FormControlLabel component so that the label occupies the same width regardless of its content. The current appearance can be seen below: https://i.stack.imgur.com/GhXed.png Below is the code I am ...