How to format numbers in JavaScript post calculations

Struggling to find a solution to format calculation results with commas for thousand separators (e.g., 10,000). After implementing the

.toLocaleString('en-US', {maximumFractionDigits:1});
method to format numbers in the output, I encountered unexpected behavior when toggling options.

var checkboxes = document.querySelectorAll('.sum')
var select = document.querySelector('#select')
var total3 = document.querySelector('#payment-total')
var total6 = document.querySelector('#payment-total2')
var total12 = document.querySelector('#payment-total3')
const totalScreenDiv = document.querySelector('#total-screen');
const totalRangeDiv = document.querySelector('#total-range');
const totalOtherDiv = document.querySelector('#total-other');
const screen1 = document.querySelector('#screen-1');
const screen2 = document.querySelector('#screen-2');
const screen3 = document.querySelector('#screen-3');
const range1 = document.querySelector('#range-1');
const range2 = document.querySelector('#range-2');
const range3 = document.querySelector('#range-3');
const other1 = document.querySelector('#other-1');
const other2 = document.querySelector('#other-2');
const other3 = document.querySelector('#other-3');



var screenwad = 5
var screenkalw = 6
var screenzat = 4
var totalscreen = document.querySelector('#total-screen')



var checkboxesTotal = 0;
var selectTotal = 0;

checkboxes.forEach(function(input) {
  input.addEventListener('change', onCheckboxSelect)
})

select.addEventListener('click', onSelectChange)

function onCheckboxSelect(e) {
  var sign = e.target.checked ? 1 : -1
  checkboxesTotal += sign * parseInt(e.target.value, 10);
  
  const summary = getSummary(e.target);
  
  var select = document.getElementById("select");
  // get selected value and assign it to the global variable selectTotal
  selectTotal = select.options[select.selectedIndex].value;
  renderTotal();
  renderSummary(summary);
}

function onSelectChange(e) {
  var value = parseInt(e.target.value, 10)
  if (!isNaN(value)) {
    selectTotal = value
    renderTotal()
  }
}

function getSummary(selectedDiv) {
  const data = {totalScreen: +totalScreenDiv.innerText.replace(',',''), totalRange: +totalRangeDiv.innerText.replace(',', ''), totalOther: +totalOtherDiv.innerText.replace(',', '')};

  const sign = selectedDiv.checked ? 1 : -1;
  if(selectedDiv.getAttribute('id') === 'styled-checkbox-1') {
    if(sign === 1) {
      data.totalScreen += +(screen1.innerText.replace(',', ''));
      data.totalRange += +(range1.innerText.replace(',', ''));
      data.totalOther += +(other1.innerText.replace(',', ''));
    } else {
      if(data.totalScreen > 0) data.totalScreen -= +(screen2.innerText.replace(',', ''));
      if(data.totalRange > 0) data.totalRange -= +(range2.innerText.replace(',', ''))
      if(data.totalOther > 0) data.totalOther -= +(other3.innerText.replace(',', ''))
    }
  } else if(selectedDiv.getAttribute('id') === 'styled-checkbox-2') {
    if(sign === 1) {
      data.totalScreen += +(screen2.innerText.replace(',', ''))
      data.totalRange += +(range2.innerText.replace(',', ''))
      data.totalOther += +(other2.innerText.replace(',', ''))
    } else {
      if(data.totalScreen > 0) data.totalScreen -= +(screen2.innerText.replace(',', ''))
      if(data.totalRange > 0) data.totalRange -= +(range2.innerText.replace(',', ''))
      if(data.totalOther > 0) data.totalOther -= +(other2.innerText.replace(',', ''))
    }
  } else if(selectedDiv.getAttribute('id') === 'styled-checkbox-3') {
    if(sign === 1) {
      data.totalScreen += +(screen3.innerText.replace(',', ''))
      data.totalRange += +(range3.innerText.replace(',', ''))
      data.totalOther += +(other3.innerText.replace(',', ''))
    } else {
      if(data.totalScreen > 0) data.totalScreen -= +(screen3.innerText.replace(',', ''))
      if(data.totalRange > 0) data.totalRange -= +(range3.innerText.replace(',', ''))
      if(data.totalOther > 0) data.totalOther -= +(other3.innerText.replace(',', ''))
    }
  }
  
  return data;
}


function renderSummary({totalScreen, totalRange, totalOther}) {
  totalScreenDiv.innerHTML = totalScreen.toLocaleString('en-US', {maximumFractionDigits:1});
  totalRangeDiv.innerHTML = totalRange.toLocaleString('en-US', {maximumFractionDigits:1});
  totalOtherDiv.innerHTML = totalOther.toLocaleString('en-US', {maximumFractionDigits:1});
}



function renderTotal() {
  //NORMAL PRICE
  total3.innerHTML = checkboxesTotal * selectTotal 
  // 10% DISCOUNT
  total6.innerHTML = (checkboxesTotal * selectTotal / 100) * (-10) + (checkboxesTotal * selectTotal)
  // 20% DISCOUNT
  total12.innerHTML = (checkboxesTotal * selectTotal / 100) * (-20) + (checkboxesTotal * selectTotal)

  //WADOWICE
}
/*PRICE LIST*/
body {
    margin: 0;
    font-family: Europa;
}
.pt_title {
    text-align: center;
    background: #2c4949;
    color: #fff;
    font-size: 20px;
    height: 60px;
    line-height: 60px;
}
.pt_months {
    color: #fff;
    background: #9B8C70;
    height: 70px;
    line-height: 70px;
}
.col-x.month {
    text-align: center;
}
.cennik .pt-container {
    padding: 0 100px;
}
.col-x {
    display: inline-block;
    width: 25%;
    float: left;
}
.pt_sub {
    background: #F4F1ED;
    height: 40px;
    line-height: 40px;
    box-shadow: 0px 1px 2px 0px #00000029;
    z-index: 9;
    position: relative;
}
.pt_sub .col-x {
    color: #352B25;
    font-size: 14px;
    font-weight: 100;
}
/*TABLE*/
.cennik ul li {
    list-style: none!important;
    float: left;
    min-width: 100%;
    background: #e6e6e6;
    border-bottom: 1px solid #00000021;
    margin-left: 0!important;
    padding-left: 0px !important;
}
.cennik ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
.pt-place {
    padding: 15px 0;
}
.pt-place .month {
    font-weight: 700;
    color: #2c4949;
}
.pt_table ul {
    display: inline-block;
    position: relative;
    width: 100%;
}
.pt-place .month span {
    font-size: 16px;
    font-weight: 700;
    color: #2c4949;
}
.pt_months .month {
    font-size: 20px;
    text-transform: uppercase;
    font-weight: 700;
}
/*CHECKBOX*/
.checkbox.col-x {
    color: #858585;
    font-weight: 700;
}
.checkbox.col-x span:hover {
    color: #354949;
}
.styled-checkbox {
     position: absolute;
     opacity: 0;
}
 .styled-checkbox + label {
     position: relative;
     cursor: pointer;
     padding: 0;
}
.styled-checkbox + label:before {
    content: '';
    margin-right: 10px;
    display: inline-block;
    vertical-align: text-top;
    width: 24px;
    height: 24px;
    background: #ffffff00;
    border: 2px solid #858585;
    border-radius: 6px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -webkit-transition: all 0.1s ease;
    -moz-transition: all 0.1s ease;
    -o-transition: all 0.1s ease;
    transition: all 0.1s ease;
}
.styled-checkbox:hover + label:before {
    background: #ffffff00;
    border: 4px solid #9B8C70;
}
 .styled-checkbox:focus + label:before {
     box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.12);
}
.styled-checkbox:checked + label:before {
    background: #9B8C70;
}
 .styled-checkbox:disabled + label {
     color: #b8b8b8;
     cursor: auto;
}
 .styled-checkbox:disabled + label:before {
     box-shadow: none;
     background: #ddd;
}
.styled-checkbox:checked + label:after {
    content: '';
    position: absolute;
    left: 6.5px;
    top: 14px;
    background: #FDF1D1;
    width: 2px;
    height: 2px;
    box-shadow: 2px 0 0 #FDF1D1, 4px 0 0 #FDF1D1, 4px -2px 0 #FDF1D1, 4px -4px 0 #FDF1D1, 4px -6px 0 #FDF1D1, 4px -8px 0 #FDF1D1;
    transform: rotate(45deg);
}
.pt-place.disabled {
    opacity: 0.5;
}
span.discount {
    color: #FFD383!important;
}
.cennik li.pt-place:hover {
    background: #f4f1ed;
}
.pt_footer {
    font-size: 14px;
    font-weight: 700;
    color: #FDF1D1;
    background: #2c4949;
    padding: 20px 0;
    display: inline-block;
    width: 100%;
}
.pt_footer span {
    color: #FDF1D1;
    font-size: 14px;
    text-transform: uppercase;
    font-weight: 700;
    letter-spacing: 2px;
}
#payment-total,#payment-total2,#payment-total3 {
    font-size: 20px;
    color: #fff;
    letter-spacing: 0px;
}
.currency {
    color: #fff!important;
    text-transform: lowercase!important;
    font-size: 20px!important;
    letter-spacing: 0px!important;
}
.col-x.spot span {
    letter-spacing: 0px;
    margin-right: 10px;
    color: #fff;
    text-transform: inherit;
    font-size: 16px;
}
.col-x.spot {
    margin-top: 5px;
}




.cennik select {
    background-color: white;
    border-radius: 30px;
    display: inline-block;
    font: inherit;
    line-height: 1.5em;
    padding: 0.5em 3.5em 0.5em 1em;
    margin: 0;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-appearance: none;
    -moz-appearance: none;
     cursor: pointer;
     font-size: 16px;
}
.cennik select.round {
    background-image: linear-gradient(45deg, #ffffff00 50%, gray 50%), linear-gradient(135deg, grey 50%, transparent 50%), radial-gradient(#ddd0 70%, transparent 72%);
    background-position: calc(100% - 20px) calc(1em + 2px), calc(100% - 15px) calc(1em + 2px), calc(100% - .5em) .5em;
    background-size: 5px 5px, 5px 5px, 1.5em 1.5em;
    background-repeat: no-repeat;
    color: #2c4949;
}

.cennik select.round:focus {
    background-image: linear-gradient(45deg, #354949 50%, transparent 50%), linear-gradient(135deg, transparent 50%, #354949 50%), radial-gradient(#ff000000 70%, transparent 72%);
    background-position: calc(100% - 15px) 1em, calc(100% - 20px) 1em, calc(100% - .5em) .5em;
    background-size: 5px 5px, 5px 5px, 1.5em 1.5em;
    background-repeat: no-repeat;
    outline: 0;
}
.cennik .checkbox {
    margin-top: 0!important;
    margin-bottom: 0!important;
}
.cennik_page .wpb_raw_code.wpb_content_element.wpb_raw_html {
    margin-bottom: -10px!important;
}
span.link {
    font-weight: 700;
}

Answer №1

After identifying three incorrect selectors in your decrement condition, I have made the necessary fixes. The issue has been resolved.

Below is the updated code:

else {
      if(data.totalScreen > 0) data.totalScreen -= +(screen1.innerText.replace(',', ''));
      if(data.totalRange > 0) data.totalRange -= +(range1.innerText.replace(',', ''))
      if(data.totalOther > 0) data.totalOther -= +(other1.innerText.replace(',', ''))
    }

[JavaScript Code Snippet]
[CSS Style Snippet]
[HTML Markup]

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

Determine the complete number of rows associated with a Model in a JQuery Data Table

How can I retrieve the total number of rows in the result set while ensuring that the datatable search functionality also works? Currently, I am only able to display the first page of results after filtering using: OFFSET AND FETCH The code snippet below ...

Decrease the gap between the <hr> and <div> elements

I currently have multiple div tags with hr tags in between, resulting in automatic spacing. I am looking to decrease this space. Please view the image link provided below for reference. [I am aiming to minimize the gap indicated by the arrow] Additionally ...

What could be the reason why both the add and remove functions are unable to work simultaneously within a JavaScript function?

Hi there! I recently started diving into JavaScript and encountered a little hiccup. I've been working on a dice game where images change randomly whenever a button is clicked. The images transition from one to another, but I wanted to add a rolling ...

The display/block feature will only function if the div element is contained within a table

I am facing an issue with hiding/showing two div elements alternatively. The code works perfectly when the divs are placed within a table, but fails when they are not in a table due to compatibility issues with Internet Explorer. I prefer not to use a tabl ...

Troubleshooting the "missing checks.state argument" error in AUTH0 debugging

I recently launched my new NextJs blog application at on Vercel, but I'm encountering some issues with getting auth0 to function properly. Upon clicking the login button located in the top right corner of the screen, users are redirected to auth0 to ...

In React development, a div (button) is visible, but in the production build, it becomes hidden from

I have been working on a website for my job, and I have added a "Gallery" button on top of two slideshows. Everything works perfectly fine on the development build, but when it comes to the production build, the button doesn't show up for some reason. ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

I am facing an issue with JQuery and AJAX where I am unable to successfully insert form data and have it return on the same

I'm currently facing an issue while trying to insert form data into a database table and then display a success or failure message on the same page. Despite my efforts, I can't seem to make it work. Below is the code snippet I am using... FORM ...

Having trouble with JSONP cross-domain AJAX requests?

Despite reviewing numerous cross-domain ajax questions, I am still struggling to pinpoint the issue with my JSONP request. My goal is simple - to retrieve the contents of an external page cross domain using JSONP. However, Firefox continues to display the ...

Struggling to dynamically fill the table with Ajax Json data

After retrieving data from my webservice call, I am sending this JSON response: [ [ { "id": 123, "vendorName": "PoppyCounter", "item": "Chocolate" }, { "id": 1234, "ve ...

Expanding the background further than the parent's width using HTML and CSS

I am looking to extend the background color or image to mimic the appearance of the example at the bottom in this jsfiddle Same code but showcased here: Example1: <div class="fixed_width"> <div class="header">Header</div> <div ...

How to toggle the visibility of specific div elements within a v-for loop depending on their content?

I am working on a scenario where I have a collection of objects displayed in a v-for loop. Each object has a specific key value pair, and I want the user to be able to toggle a button outside the loop to show or hide elements based on that key value. Initi ...

Display unique information according to the value in the form field (email domain)

I've developed an innovative ajax signup form that integrates jQuery and CSS3. The unique feature of this form is its multi-step process. In the first step, users are required to enter their email address and password. What sets this form apart is i ...

Creating a dynamic MPTT structure with expand/collapse functionality in a Django template

I am looking for a way to display my MPTT model as a tree with dropdown capability (open/close nodes with children) and buttons that can expand/collapse all nodes in the tree with just one click. I have searched for examples, but the best I could find is ...

Verify the occurrence of a search result and if it appears more than once, only show it once using JavaScript

Hello all. Currently, I am developing an online users script using NodeJS and SocketIO. The functionality works fine, however, I am encountering an issue where if a user connects from multiple browsers, windows, or devices, it displays duplicate results li ...

What is the method for providing external parameters to a JOI extension?

Perhaps JOI may not be the ideal tool for this particular task, but I am interested in utilizing it if feasible. Essentially, I have a scenario where a user is sending a request to an API to store specific metric data. Certain metrics are restricted based ...

Link JSON in JavaScript using field identifiers

I've been working on incorporating JSON data into my JavaScript code, and the JSON structure I am dealing with is as follows: { "status":"ok", "count":5, "pages":1, "category":{ "id":85, "slug":"front-page-active", "title":"Front ...

Tips for implementing a "loading spinner" for each new ajax call using jQuery

Each time an ajax call is made, I want to display the loading icon/image. However, in my current code, the image only appears once and then disappears. Even when there are multiple ajax calls within a for loop, the image only shows once and vanishes after ...

Access a local website path using JavaScript upon opening the browser

I need a Javascript function that can determine the day of the week when my html file is accessed, allowing me to automatically open a specific sub-page within my project. ...

Is there a way to make sure all source code is aligned to the left?

I'm interested in enhancing the appearance of the source code on my WordPress website. Currently, it looks cluttered with unnecessary empty lines and alignment issues. Is there a way to optimize the source code so that everything is left-aligned and ...