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

Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate acc ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

Ways to style a div element in CSS to achieve a unique shape

Hello there! I'm looking to achieve a tilted background div effect. Anyone have any tips or ideas on how I can do this? I'm new to web development and would appreciate the guidance. https://i.stack.imgur.com/wyj1X.png ...

Script malfunctioning following an AJAX request

My page consists of a header where all my javascript is located. Within the body of the page, there is a link that triggers an ajax http request using vanilla JavaScript (not jQuery). This request retrieves a PHP form and injects it onto my page. The PHP ...

Is there a way to efficiently add delimiters to an array using jquery dynamically?

Just joined this community and still figuring things out. I have a question - how can I use jQuery to dynamically add a delimiter like "|" after every 3 elements in an array? This way, I can explode the array and utilize the resulting arrays separately. He ...

I am eager to display this JSON data using AngularJS tables

I have JSON file with content about categories, departments, and digital marketing: { "categories":[ { "dept_id":"123", "category_name":"database", "category_discription":"list of database", "current time ...

An error notification received from the command "jspm install jquery"

As I follow the tutorial on the jspm.io site, everything goes smoothly until I reach step 3. When I try to execute jspm install jquery, an error message pops up. The error reads: warn Error on getOverride for jspm:github, retrying (2). ReferenceError: ui ...

Tips for selecting a JSON data node on-the-fly using jQuery

This is an example of my ajax function: $.ajax({ type: "GET", dataType: "json", async: false, url: "/wp-content/comment_data.php", data: 'songid=' + $array, success: function(data){ oTable.find('td').eac ...

Float over a specific line in a drawing

I am looking to develop a unique rating system using css, html, and potentially js : My goal is for the user to hover over a specific section of a circular stroke and have it fill with a particular color, all while maintaining functionality. So far, I hav ...

In search of a resolution for the error message "multipart: NextPart: bufio: buffer full" while attempting to upload an image via a fetch post request. Can anyone provide guidance

What steps can be taken to resolve the issue "multipart: NextPart: bufio: buffer full" when using a fetch post request to upload an image? I have a feature on my website that allows users to upload profile pictures. I use a fetch post request for this pur ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

The encodeURIComponent function does not provide an encoded URI as an output

Looking to develop a bookmarklet that adds the current page's URL to a specific pre-set URL. javascript:(function(){location.href='example.com/u='+encodeURIComponent(location.href)}()); Even though when I double encode the returned URL usin ...

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Tips for creating a responsive Livewire Pagination system

Looking to make Livewire pagination responsive? When using Bootstrap, simply add flex-wrap to the pagination class to ensure responsiveness. Component: class Index extends Component { use WithPagination; protected $paginationTheme = 'bootstr ...

What is the best way to require users to click one of the toggle buttons in a form?

Is it possible to require the user to click one of the toggle buttons in a React form? I want to display an error if the user tries to submit the form without selecting a button. Even though I tried using "required" in the form, it didn't work as expe ...

Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced en ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

How can I pass GET data and make it accessible in another PHP page through ajax?

After gaining access to www.mysite.com/index.php?order_by=id asc I need to send $name AND $_GET[order_by] to autoload_process.php. How should I proceed? . . . The contents of index.php are as follows: <!DOCTYPE html> <html> <head> ...