Determine the overall price of the items in the shopping cart and automatically show it at the bottom without the need for manual entry

Creating a checkout form that displays the total cost of products, subtotal, GST cost, delivery cost, and overall price. The goal is to calculate the total by adding together the costs of all products with the "price" class (may need ids) at a 15% increase from the subtotal plus delivery.

The checkout form layout may include irrelevant styling inherited from the website's page.

I would appreciate advice on implementing this functionality. I believe assigning ids to each product, using getElementById to retrieve values, and calculating the total amount would be the way to go, but not sure how to execute it.

<head>
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'>
  <script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>
<main>
  <div class='payment-form'>
    <div class='checkout-tabs'>
      <div class='details-field'>
        <div class='details-inputs'>
          <h3>Accepted Payment Methods</h3>
          <div class="icon-container">
            <i class="fab fa-cc-visa"></i>
            <i class="fab fa-cc-mastercard"></i>
            <i class="fab fa-cc-apple-pay"></i>
            <i class="fab fa-cc-amazon-pay"></i>
            <i class="fab fa-cc-paypal"></i>
          </div>

          <label><i class="fa fa-user"></i> Full Name</label><input class='input-field ' type="text" placeholder="John Doe">
          <label><i class="fa fa-phone-alt"></i> Phone Number</label><input class='input-field ' type="text" placeholder="(###) ###-####">
          <label><i class="fa fa-envelope"></i> Email</label><input class='input-field ' type="text" placeholder="john@example.com">
          <label><i class="fa fa-institution"></i> City</label><input class='input-field ' type="text" placeholder="San Francisco">
          <table class="half-input-table">
            <tr>
              <td>
                <label for="Country"><i class="fa fa-globe"></i> Country</label><input class='input-field ' type="text" id="Country" name="Country" placeholder="USA">
              </td>
              <td>
                <label for="zip"><i class="fas fa-map-marker-alt"></i> Zip Code</label><input class='input-field ' type=&ldqu...;

Answer №1

If you want to select multiple elements at once, consider using querySelectorAll

For instance:

// Select all elements with the '.price' class
const prices = document.querySelectorAll(".price");

You can then iterate over the prices array using array.reduce()

// Convert the nodeList into an array and loop through it
let total = [...prices].reduce((acc, price) => {
    return acc + parseFloat(price.innerHTML);  
}, 0);

This approach might require modifications in the HTML structure

Changing from:

<div class='price'>$429.00 (GST Inc)</div>

To something like:

<div><span>$</span><div class='price'>429.00</div> <span>(GST Inc)</span></div>

Alternatively, you can utilize a regular expression on the price.innerHTML

Answer №2

It's unnecessary to include an ID since IDs must be unique.

I don't see your delivery details on the page, so here is the total.

Please note: Your HTML structure appears to be incorrect. Divs cannot be placed within spans. It is recommended to have the stylesheet as an external file and include it at the beginning of the head section.

const prices = [...document.querySelectorAll(".order-info .price")]
  .map(price => +price.textContent.replace(/[^\d|.]/g, "")) // remove text and currency symbols

const sum = prices.length > 0 ? prices.reduce((a, b) => a + b) : 0; // calculate total price

console.log(sum.toFixed(2)); // display total sum

const costs = [...document.querySelectorAll(".cost_sum div")];
const total = costs.length > 0 ? costs.reduce((acc, cost) => {
  acc += +cost.textContent.replace(/[^\d|.]/g, "");
  return acc;
}, 0) : 0;

console.log(total.toFixed(2))
body {
  background-color: #424242;
}

/* Other CSS styles removed for brevity */
 
<head>
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'>
  <script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>
<main>
  <div class='payment-form'>
    <div class='checkout-tabs'>
      /* Checkout tabs content removed for brevity */

              TOTAL
            </div>
            <button class='checkout-button'>Checkout</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

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

Finding a specific cell in a Django HTML table: tips and tricks

Recently delving into django and its intricacies. Struggling to grasp the concept of accurately pinpointing a specific cell within an html table. Yearning to modify the background color of select cells based on certain conditions derived from the generate ...

Optimizing the performance of inline functions

I've been experiencing a minor performance issue with inline functions. Take a look at the code snippet below:- inline int left(int x) { return 2*x; } inline int right(int x) { return 2*x+1; } main() { for(int i=0;i<200000000;i++) { ...

The issue arises when trying to escape double quotes within a regex pattern using ng-pattern

My ng-pattern validation includes a regex pattern ^[^\./:*\?\"<>\|]{1}[^\/:*\?\"<>\|]{0,254}$ to prevent invalid characters in file paths and set a limit. However, when I specify the ng-pattern as: ng-p ...

Tips on how to trigger the function upon receiving the response value by concurrently running two asynchronous functions

export default { data: () =>({ data1: [], data2: [], lastData: [] }), mounted() { asynchronous1(val, (data)=>{ return this.data1 = data }) asynchronous2(val, (data)=>{ return this.data2 = data }) f ...

Modify the class of an input while typing using Jquery

Recently, I created a form using Bootstrap 4. The validation process is done through a PHP file with an AJAX call and it's functioning correctly, except for one issue. I want the input class to switch from "invalid" to "valid" as soon as the user begi ...

Incorporating Ruby on Rails: Sending a fresh POST request to API and instantly

I'm a beginner in the field of ruby on rails. Our website allows users to search and receive a list of results. Now, I want to incorporate sorting functionality for the results (by price, rating, etc). The API handles the sorting process, so all I ne ...

When applying a maximum width of 100% with automatic height, images may become cropped

I'm a beginner in learning CSS, and since my technical skills are limited, I'll try to keep things simple. Currently, I have an image taking up half of the screen with the following CSS code that I found after reading some articles: <div class ...

Alert: '[Vue warning]: Directive "in testing" could not be resolved.'

Currently, I am running unit tests within a Vue 2.0 application using PhantomJS, Karma, Mocha and Chai. Although the tests are passing successfully, I am encountering a warning message with each test indicating an issue like this: ERROR: '[Vue warn ...

Prevent random files from being included in RequireJS's r.js optimization process and instead load them asynchronously

Currently, I have successfully implemented RequireJS and a Grunt-based build process that optimizes my JS app into one file using r.js. This consolidation of all app files has proven to be efficient for production deployment. However, the issue arises wit ...

How can I create a CSS animation for a box element?

During my current project, I have the task of creating a box that will display an animation within 2 seconds and move from one corner to another. What is the most straightforward way to achieve this? ...

How can I send back multiple error messages from a pug template in a node.js application with Express?

I am currently working on validating inputs from a form on a Node.js web server using Pug.js and Express.js. The issue I am facing is that when there are multiple problems with the user's input, only the first error is displayed to the user. How can I ...

After extended periods of use, the website experiences frequent crashes

Currently, I am developing a website using a free provider (000webhost) and focusing on integrating a chat feature. To achieve this, I have implemented an interval every 500 milliseconds that reads a file to check for new messages. When a new message is de ...

Having difficulty including my JavaScript file located in /app/assets/javascripts when using Rails 4 and "//= require_tree ." in application.js

I'm currently attempting to implement a d3.js graph into my Rails 4 application by following a tutorial found on this website. The example application provided on GitHub works perfectly as expected. The issue I am facing is that when I try to recreat ...

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

When pasting Arabic text into an input box, the words in HTML appear to be jumbled and shuffled around

When I replicate this text يف عام and input it into a box, the output is shown as follows عام يف ...

My code gets disrupted when I switch between ids and classes

I'm currently learning about javascript and jquery, attempting to implement various scripts. I successfully executed the following script: jQuery(document).ready(function($) { var scroll_start = 0; var startchange = $('#homepage-header' ...

Inscribe latitude from marker onto input field

Currently, I am working on a feature where markers are added to Google Maps API v3 by clicking on the map. Each marker then displays its coordinates in an info window. However, I am facing an issue with picking up the latitude and longitude values and inse ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? state constructor(props) { super(pro ...

The pseudo right arrow is failing to display in the vertical center

My pseudo right arrow is not displaying vertically centered within the .nav-link class. Can anyone suggest how I can achieve vertical alignment for my right arrow in an <a> tag? I have already attempted using top:50% but it did not work. Here is th ...

What is the best way to manage individual properties in React (Next.js)?

import React from 'react'; import { makeStyles} from '@material-ui/core/styles'; import {Select, MenuItem} from '@material-ui/core'; import useState from 'react'; const sample = () => { const data = [ {TITLE : & ...