Price update feature is functioning correctly, however it does not support multiple select options and discounting the final price

I currently have several dropdown menus that calculate a total price at the end. While it's working well, I am facing a few challenges.

Firstly, I want to incorporate additional prices into the calculation. The breakdown should be as follows:

Total: £20.97

V.A.T: £4.19

Total Amount: £25.16

I believe this is a simple task but I can't figure out how to do it?

Secondly - The calculation only works with single selection drop down lists. If I try to select multiple options in one list, it only calculates one.

Here is the code I am using for the price calculation:

$(function(){
    $(".calculate").on("change", function(){
        var total = 0;
        $('.calculate').each(function() {
            if($(this).val() != 0) {
                total += parseFloat($(this).val());
            }
        });
        $('#total').text('£' + total.toFixed(2));
    });

});//]]>

Thirdly, I have around 8 dropdown lists. However, I want the last one to offer a discount on the total price instead of adding to it. The code mentioned above takes the price from option value of each selection, including the discount amount (listed as 10% in the discount column of the database).

Essentially, after selecting from the first 7 lists and getting a total of, let's say, £20.97, once the last list is selected, the price should be replaced with a discounted amount like (-10%) £18.87.

I am almost done with this project but struggling with this final hurdle.

Thank you

Answer №1

When dealing with a SELECT element that allows for multiple selections, the jQuery val() function will return an array of values. To handle this scenario in your code, you need to check if val() returns an array and then iterate through the array to add up all the items. Here's one approach:

$('.calculate').each(function() {
    var currentValue = $(this).val();
    if (currentValue.length != undefined) {
        for (var i = 0; i < currentValue.length; i++) {
            if (currentValue[i] != 0) {
                total += parseFloat(currentValue[i]);
            }
        }
    }
    else if(currentValue != 0) {
        total += parseFloat(currentValue);
    }
});

This snippet should account for multiple select options. As for applying a discount, simply retrieve the value from your final SELECT and subtract the discount accordingly:

var discount = parseFloat($('.discount').val()) / 100;
total = total - (total * discount);

Answer №2

Does the JavaScript fetch the values from the DDL in the Database or are they manually inputted into the form?

The calculation for the percentage is done by multiplying 20.97 by 0.10. Since the 10% is hardcoded, it should accurately reflect in the final dropdown list.

Furthermore, aside from inputting values into the form and doing the percentage calculation, I'm uncertain about where the issue lies. Additional information may be helpful in pinpointing the problem...

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

Making a call to a recently generated document in Firestore

After adding a new document, how do I access its data property? For instance: https://firebase.google.com/docs/firestore/manage-data/add-data // Add a new document with a generated id. let addDoc = db.collection('cities').add({ name: 'To ...

Storing Firebase Auth User references in a Firestore document: Tips and Tricks

I have developed an application that allows users to register and login, using Firebase Auth for authentication. In addition to Firebase Auth, I also utilize Firestore to manage multiple collections like "Requests" and "Offers". A user authenticated with ...

Whenever I work with NPM, node.js, and discord.js, I consistently encounter the error message stating "TypeError: Cannot read property 'setPresence' of null."

I'm developing a Discord bot with NPM and discord.js, but I keep encountering an error that says "TypeError: Cannot read property 'setPresence' of null". Here is my bot code: const Discord = require('discord.js'); const { prefix, ...

Creating a conditional interface based on props in TypeScript: A step-by-step guide

What is the most effective way to implement conditional props in a component that can be either a view or a button based on certain props? Let's take a look at an example called CountdownButtonI: class CountDownButton extends Component<CountdownBut ...

Is it possible to determine if the selected/clicked element is a multiple of "n" using jQuery?

If I have 'n' li elements within a ul, I am looking to trigger an alert message only when the li item that is selected or clicked on is a multiple of "n" (for example 3). In this scenario, the alert should only appear if I click on the 3rd, 6th, ...

Is it possible to revert an image back to its original state after it has been altered on hover

I am currently experimenting with jQuery to create an image hover effect where hovering over one image changes the other. I've managed to accomplish that part successfully. However, I'm struggling with how to make the original image revert back w ...

Is there a constraint on JSON data?

Is there a limit to the amount of data that JSON with AJAX can handle in outgoing and returning parameters? I am trying to send and receive a file with 10,000 lines as a string from the server. How can I accomplish this task? Can a single parameter manage ...

Refresh the arrangement by dragging and dropping the positions

Is there a way to reset the positions of dragged items back to their default positions, similar to how they were when the page initially loaded? For instance, after clicking on a button.. Here is a link to the jsfiddle example: https://jsfiddle.net/dj ...

What steps can be taken to ensure that a function is executed in order to delegate the process forward?

In my JavaScript code, I have a series of functions that need to be executed in a specific order. One function may return a value synchronously, while others do not return anything or return an Observable result asynchronously. How can I ensure that each ...

How can I personalize pagination with the reactable library?

As I work on implementing pagination for a reactable table, I have referred to the documentation which clearly outlines how to add this functionality using itemsPerPage and pageButtonLimit: <Table className="table" data={[ { Name: 'Griffin Smi ...

Pass a variable through AJAX during page load

I attempted to implement code for sending a variable from the view to the controller, but unfortunately my code is not functioning and I am encountering an error. An error message stating: Uncaught ReferenceError: $ is not defined is being displayed. V ...

Implementing file previews in ReactJS with file paths

Looking for a way to showcase the first page of a file as a thumbnail using reactjs within each Card element from the ANTD UI framework, here is an example: <Card> <a href={file.path}></a> </Card> Important to note: The file p ...

"Activating Backticks for MySQL CodeIgniter Active Record: A Step-by-Step Guide

I am experiencing an issue with CodeIgniter's active record when trying to update a field named Dec (Jan - Nov updates were successful)... Here is the code I am using: $this->db->set($month,"$month+$tax", FALSE); $this->db->set('to ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

How can you verify the existence of a database in MySQL?

I am in the process of checking for the existence of a database with a specific name and creating it if it does not already exist. My preference is to accomplish this task using VBScript. Currently, I am attempting to achieve this by performing a loop se ...

What is the best way to save a current HTML element for later use?

Here is a simple HTML code that I would like to save the entire div with the class test_area and then replicate it when needed. Currently, my goal is to duplicate this div and place the clone underneath the original element. How can I achieve this? Unfortu ...

Executing a message in Azure Service Bus using Javascript/Node.js

I am utilizing the @azure/service-bus library in a Node.js application to receive messages. The code I am using is as follows: const { ServiceBusClient } = require("@azure/service-bus"); const sbClient = new ServiceBusClient(connectionString); ...

Escape from an iframe with the help of a buster

My website is being targeted by a code that prevents it from breaking out of an iframe. Despite trying different frame breaker scripts, I have not been successful in resolving this issue. Any assistance would be greatly appreciated. Thanks! Buster: func ...

Which is better: leveraging MySQL subqueries or utilizing PHP processing capabilities?

My query resembles the following: Select tradesmen.id, (SELECT COUNT(quotes.id) FROM quotes WHERE quotes.tradesman_id = tradesmen.id) AS quoted From tradesmen; In essence, there is a subquery for each row in the database, which totals over 5 ...

Issues with Gulp and Browser Sync integration

Encountering errors while running Gulp with Browser Sync in Chrome: NonESPMessageInterface --- nonEspMessageInterface.js:8 TypeError: Cannot read property 'insertBefore' of null --- angular.js:13708 Checklist message was invalid, from origin # ...