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

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

Having trouble sending form data using the jQuery AJAX POST method?

I am facing an issue with a simple form that is supposed to send data to PHP via AJAX. However, when I submit the form, the data does not get sent across. Here is the JavaScript code: $(document).ready(function(e) { $('#update').submit(func ...

What methods does the W3C CSS Validator use to recognize a CSS3 document?

Help Needed! Can someone tell me how to specify a CSS3 file for validation by the W3C? In HTML5, we use <!DOCTYPE html>, but what should we use in a CSS file? Whenever I try to validate my CSS file containing CSS3 elements like @font-face and box- ...

Managing Ajax error messages

$.getJSON("data.php", function(data) { ... this callback is for handling successful retrieval of data }); What is the best way to manage errors in relation to the ongoing $.getJSON request? ...

The index on ref in MongoDB does not seem to be yielding any improvements

I've encountered a performance issue with my model: const PostSchema = new mongoose.Schema( { _id: mongoose.Schema.Types.ObjectId, workSpace: { type: mongoose.Schema.Types.ObjectId, ref: 'Workspace&apos ...

AngularJS simplifies request handling by allowing currying of requests

I am working with three forms within the same container, each triggered by a specific objectId. I want to create a function that can handle all actions related to these objectIds. Unfortunately, I am restricted to using ES5. var applyActions = function( ...

Customize Individual Rows in a React DataGrid

I am exploring the world of Material UI React data grid for the first time, and I am looking to add a unique background color to only the initial three rows. Each row should have a different color scheme that remains static, without any interactions trigge ...

Creating a template based on an object type in JavaScript with Angular: A step-by-step guide

I have a collection of objects, each with a property indicating its type. Here's an example: [ { "type" : "date", ... },{ "type" : "phone", ... },{ "type" : "boolean", ... } ] I'm ...

Develop a unique method for loading AngularJS templates

When working with AngularJS, there are various ways to provide an external template, such as using a script tag or a separate HTML file on the web server. However, I am faced with a situation where I need to implement a custom logic for retrieving these ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...

Establishing the REM value for all CSS properties

My goal is to implement the use of rem units throughout my website. However, relying on the standard rem-to-px conversion rate doesn't feel very intuitive: 10px = 0.625rem 12px = 0.75rem 14px = 0.875rem 16px = 1rem (base) 18px = 1.125rem 20px = 1.25r ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

What causes an "Undefined index" error in jQuery when making AJAX requests?

Whenever I make an AJAX request in my main.js file, I encounter the following error message: Undefined index: id in sqlinfo.php on line 13 I am puzzled because I believe that I am populating the request object correctly. What's even more perplexing i ...

Executing numerous GET requests with varying parameters in AngularJS

Update: My apologies to those who answered, it turns out that the code was correct, but requests were being intercepted and losing all parameters. I am attempting to send repeated HTTP GET requests to a REST API based on the response, using the solution I ...

Implementing Angular2 with conditional loading

One of the requirements for my project is to redirect users to the login page before loading the Angular2 application, without actually loading it. The project is built using angular2-quicksart. After minifying the Angular2 js file: <script> va ...

Obtaining material for optimizing a dynamic image

I'm facing a challenge with my responsive image setup. The image is filling the top half of the screen as intended, but I can't seem to get the content underneath it to stay below the image as it resizes. Instead, the content ends up overlapping ...

There seems to be an issue with the syntax in ReactJS: the URL is

I'm facing an issue in my React code. I have a function that doesn't seem to be in the correct format for React. check(img) { console.log(img,typeof img) const url=""; const arrN = ["15","16","35","36","37","38","39","40" ...

Elevate a div over another div

I have a situation where I need to nest two divs inside another div with the ID "video-wrapper". Here is the HTML code: <div class="row"> <div class="video-wrapper col-lg-2"> <div class="video-thumbnail"> <img ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

Removing white spaces from response HTML in JBoss 5.1 version

Does anyone know of a JBoss 5.1 plugin or utility that can automatically strip leading and trailing white spaces from HTML being sent as a response? Similarly, is there a way to do this for JSP files upon deployment? Any application-specific settings would ...