Dynamic JavaScript Total Calculation

I have been struggling to update the total price for specific options. Even though the code was created by someone else and has worked fine for many users, I can't seem to make it work correctly. Any assistance would be greatly appreciated.

Here is the code I am currently using:

HTML

<form name="cart_quantity" action="" method="post">    
  <h4>Available Options</h4>
  <p>
    <input type="hidden" id="hid_id[7]" value="0"> <select id="id[7]" name="id[7]" required aria-required="true" onchange="changePrice(this.id)" class="form-control">
      <option value="" selected="selected">--- Please Choose ---</option>
      <option value="48">1 x nVidia RTX 2080 Ti 11GB GDDR6 blower fan design (+$1,800.00)</option>
      <option value="49">2 x nVidia RTX 2080 Ti 11GB GDDR6 bblower fan design (+$3,600.00)</option>
      <option value="50">3 x nVidia RTX 2080 Ti 11GB GDDR6 blower fan design (+$5,400.00)</option>
      <option value="51">4 x nVidia RTX 2080 Ti 11GB GDDR6 blower fan design (+$7,200.00)</option>
      <option value="27">Not needed</option>
    </select>
  </p>

  <p>Options subtotal: <span id="productPrice"></span></p> 
</form>

Javascript

  var actualprice = document.getElementById('productPrice').innerHTML;
  var actualInd = actualprice.indexOf("(");
  var price = actualprice.substring(actualInd + 1, (actualprice.length));
  var total = price.match(/[\+\-]*(\d+)\.(\d+)/)[0];

  function changePrice(id) {
    var select_list_field = document.getElementById(id);
    var select_list_selected_index = select_list_field.selectedIndex;
    var text = select_list_field.options[select_list_selected_index].text;

    var ind = text.indexOf("(") + 1;
    var str = text.substring(ind, text.indexOf(")"));
    if (str != '') {
      str = str.replace(',', '');
      str = str.replace('$', '');
      str = str.match(/[\+\-]*(\d+)\.(\d+)/)[0];
    };
    var hFieldId = "hid_" + id;
    var hiddenField = document.getElementById(hFieldId).value;
    if (str == "choose") {
      if (isNaN(hiddenField)) {} else {
        total = total - hiddenField;
      };
      document.getElementById(hFieldId).value = 0;
    } else {
      document.getElementById(hFieldId).value = str;
      if (hiddenField > 0 || hiddenField < 0) {
        total = total - hiddenField;
      };
      if (isNaN(str) || (str.length === 0)) {
        total = parseFloat(total);
      } else {
        total = parseFloat(str) + parseFloat(total);
      };
      var $total_display = 0;
      if (total < 0) {
        total_display = 0;
      } else {
        total_display = total;
      }
    }
    document.getElementById('productPrice').innerHTML = actualprice.replace(/[\+\-]*(\d+)\.(\d+)/, total_display.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")); //Version 1.2.3
  }

Answer №1

Before proceeding, it would be helpful if you could provide details on what you have already attempted.

In my opinion, the following code snippet appears to be poorly structured:

var actualprice = document.getElementById('productPrice').innerHTML;
var actualInd = actualprice.indexOf("(");
var price = actualprice.substring(actualInd + 1, (actualprice.length));
var total = price.match(/[\+\-]*(\d+)\.(\d+)/)[0];

Utilizing `if` statements and setting default values can assist in debugging and maintaining the functionality of your code.

var actualprice, actualInd, price, total, total_check;
actualprice = document.getElementById('productPrice').innerHTML;
actualInd = actualprice.indexOf("(");
if (actualprice.length === 0) {
    actualprice = 0;
    console.warning("html usage issue ");
}

if (actualInd < 0) {
    actualInd = 0;
    console.warning("indexOf usage problem ");
}

price = actualprice.substring(actualInd + 1, (actualprice.length));
total_check = price.match(/[\+\-]*(\d+)\.(\d+)/);

if (!total_check) {
    total = total_check[0];
} else {
    console.error("an error occurred");
}

Relying solely on traversing the DOM for all information may not be the most efficient approach from my perspective.

Consider this alternative example:

  <option value="" selected="selected">--- Please Select ---</option>
  <option value="48">1 x nVidia RTX 2080 Ti 11GB GDDR6 blower fan design (+$1,800.00)</option>


actualprice.indexOf("(");

Wouldn't a cleaner solution look like this?

 <option value="48" data-price-tag="18000.00">1 x nVidia RTX 2080 Ti 11GB GDDR6 blower fan design (+$1,800.00)</option>

price = <element selection>.dataset.priceTag;

I personally see several issues with that particular script. Here are some resources that I believe could aid in improving your understanding:

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

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

Clicking on "li" to activate and deactivate

Currently utilizing: $('#btnEmpresarial').attr('onclick','').unbind('click'); In order to deactivate a read using javascript.. However, I now require enabling the onclick after the function has completed. Is ther ...

Encountering a problem while verifying pattern using regular expressions

I'm facing an issue when manually checking if my inputs match the specified patterns. Below is the function I am using for this check: if (!$element.attr("pattern")) return true; let pattern = $element.attr("pattern"); le ...

Is JavaScript capable of producing different results with the same input?

I am currently revising one of my scripts and have come across a perplexing issue. The variable command is an input, and I conducted the following test with identical regular expressions: var parts = command.match(/([^\s"]+(?=\s*|$))|(".+?")/g); ...

The disappearance of the overlay background due to modal reload in NextJS dynamic routing

I am working on a simple NextJS app where clicking on a page opens a modal with updated URL but without triggering a new navigation. The content inside the modal is displayed, while the actual page location is reflected in the URL and refresh takes the use ...

Navigating smoothly through different URLs to a single state using Angular's UI-Router

I recently started using angular's ui-router and I am looking for a way to configure multiple URLs to point to the same state. For instance: /orgs/12354/overview // should show the same content as /org/overview Currently, my $state provider is set u ...

Is Jquery not tallying up the numbers accurately?

Looking to secure a ticket with a complimentary offer? Here are the guidelines: A single individual can purchase 1 or more tickets, but the maximum is 4 An offer of at least 1 euro can be made for tickets, with no upper limit. For instance, if 4 tickets ...

Error message: "Issue with Jointjs library on Node.js server - Uncaught ReferenceError: Joint is not recognized"

I am attempting to create a sample diagram using the code below on a file hosted on a Node server: <!DOCTYPE html> <html> <head> <title>newpageshere</title> <link rel="stylesheet" href="joint.css" /> <script src="j ...

How can one go about incorporating the feature "updating list upon clicking a label" on a webpage?

On my website, I currently display a comprehensive list of publications. However, I am looking to organize these publications by various research topics using labels. Ideally, when clicking on a specific label, only the papers related to that topic will be ...

What is a more streamlined approach to creating a series of methods and functions that alter a single variable consecutively?

My JavaScript project involves handling sub-arrays within a long data file that cannot be altered. The data, stored in a variable named data, is retrieved via a script tag with a specified URL property. I need to extract and modify specific sub-arrays from ...

Exploring new classes with jQuery's .not() and :not()?

I am working on a memory game where I need to flip cards and check if two are equal. My issue is that I do not want the function to run when clicking on a card that is already flipped, or on another flipped card. I tried using jQuery's .not() and :no ...

Troubleshooting issues with Angular's scope functionality

Here is my controller: angular.module('app', []) .controller('ctrl', ['$scope', function ($scope) { $scope.daysPerMonth = new Date(year, month).getDate(); }] ); This is the corresponding html: <div ng-app> <h1&g ...

Unexpected syntax error occurs while retrieving data from web API using jQuery AJAX request

I'm attempting to retrieve a json object from the following URL: You may not understand much as it's in Greek, but the format is json. Below is the code snippet I'm using: function getDicts() { api_url = 'https://test3.diavgeia.gov ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

Troubleshooting: Why is my switch-case statement in TypeScript not functioning as expected

Here is a simple switch case scenario: let ca: string = "2"; switch (ca) { case "2": console.log("2"); case "1": console.log("1"); default: console.log("default"); } I am puzzled by the output of this code, which is as follows: 2 1 defa ...

Count in JavaScript that picks up where it left off

I'm working on setting up a countdown timer that runs for 24 hours, showing the days, hours, minutes, and seconds. The challenge I'm facing is how to save the progress of the countdown. Essentially, I want it to resume from where it left off for ...

Improprove jQuery code to eliminate redundancy

Is there a better way to improve the appearance of this code? Here is a condensed snippet of the HTML: <div id="template" style="display:none;"> <div style="position:relative;"> <fieldset> <img class="sm_kont" ...

Vuetify: The checkbox displays the opposite status of whether it is checked or unchecked

Can you help me simplify this problem: In my Vue.js template using Vuetify components, there is a checkbox present: <v-checkbox v-model="selected" label="John" value="John" id ="john" @click.native="checkit"> </v-checkbox> ...

Protractor: Decrease the magnification

Currently, I am working with protractor and facing the challenge of zooming out to 50%. Despite trying numerous solutions found on StackOverflow, none have successfully resolved the issue. Some attempted solutions include: browser.actions().keyDown(protra ...