Performing calculations involving both select and checkbox input values, as well as handling negative numbers

Seeking assistance in creating a feature where users can select a billing term from a dropdown and then choose checkboxes to add to the total. While it works fine on JSFIDDLE, I encounter issues on my website - specifically when selecting all checkboxes, resetting the total to 0 by choosing 'Choose billing term', and unchecking all options leading to negative numbers. Any suggestions on how to resolve this issue? Even checking and unchecking options results in negative numbers.

HTML:

<div class="payment-term">
  <label>Billing period:</label>
  <select id="billing-price" name="billing-term" class="selectpicker">
    <option value="0">Choose billing term</option>
    <option value="300">12 Months: $300/mo. (Save 20%)</option>
    <option value="350">1 Month: $350/mo.</option>
  </select><br><br>
  <label>Extra Features ($50/month): </label>
</div>

<section id="extra-features">
  <div class="span3">
    <label class="checkbox" for="Checkbox1">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Instagram
    </label>
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Review site monitoring
    </label>
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Google+
    </label>
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> LinkedIn
    </label>
  </div>
  <div class="span3">
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Pinterest
    </label>
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> FourSquare
    </label>
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Tumblr
    </label>
    <label class="checkbox">
      <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Advertising
    </label>
  </div>
</section>

<div class="card-charge-info">
  Your card will be charged $<span id="payment-total">0</span> now, and your subscription will bill $<span id="payment-rebill">0</span> every month thereafter. You can cancel or change plans anytime.
</div>

Javascript code:

var select = document.getElementById('billing-price');
select.addEventListener('change', updatePrice, false);
var price = 0;
var additional = 0;

function updatePrice(e) {
    price = parseFloat(select.value);
    document.getElementById('payment-total').innerText = price + additional;
    if (price == select.options[2].value){
    document.getElementById('payment-rebill').innerText = 0 + additional; 
    } else {
    document.getElementById('payment-rebill').innerText = price + additional;
    }
}
var inputs = document.getElementsByClassName('sum'),
    total  = document.getElementById('payment-total');
    total2 = document.getElementById('payment-rebill');

for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var add = this.value * (this.checked ? 1 : -1);
        additional += add
        total.innerHTML = price + additional
        total2.innerHTML = price + additional
    }
}

Check out the working jsfiddle here: http://jsfiddle.net/uZbee/2/
Visit my site (not functioning correctly):

I have implemented a custom javascript file for better checkbox appearance, which might be affecting the calculation of checked boxes in my javascript code.

Answer №1

An error in the code is leading to negative values due to not validating the input before using this.checked at this particular line.

The calculation var add = this.value * (this.checked ? 1 : -1); always returns false, resulting in a negative added value.

To resolve this issue, consider changing this.checked to

this.parentNode.className.split(" ").indexOf("checked") > -1
.

for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var updatedAddition = this.value * (this.parentNode.className.split(" ").indexOf("checked") > -1 ? 1 : -1);
        additional += updatedAddition;
        total.innerHTML = price + additional;
        total2.innerHTML = price + additional;
    }
}

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

Vue 3 array filtering does not result in a new array being generated

I'm a bit confused about the behavior in Vue 3 when filtering a reactive array to create a new array and then modifying the new array, why does it update the original one? Shouldn't the filter operation generate a completely separate array with n ...

Web Browser cross-origin AJAX requests

Recently, I developed an Internet Explorer extension that injects a script every time a page is accessed. The purpose of this script is to send an AJAX request to my localhost. However, I have encountered a roadblock where the request only works if it&apos ...

Retrieve the webpage address, search parameters, and anchor symbols

I have a form input where users enter a valid URL. My goal is to extract the URL, query string (if provided by the user), and hash value (if provided) separately. This is what I currently have: var url = userInput.split('?')[0]; //get url v ...

Conceal a div when the Bootstrap toggle is in the active

Is it possible to hide a div when the bootstrap toggle div is active? if($('data-toggle').is('collapse')){ $("#Div1").hide(); } else{ $("#Div1").show(); } ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

Issue with splitting an array and eliminating commas - angular/ReactJS

Console Error: Unhandled error during execution of mounted hook Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split') It seems to work up until it comes across a group that has no data for continent. This looks ...

The positioning of divs shifts when adjusting the width of the screen

I'm having trouble creating a design similar to the one in this image. When I adjust the browser width, two divs don't remain aligned properly. If I use float: left for both divs, they stack vertically, but the layout breaks when I resize the scr ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

Tips for delaying code execution until environment variables are fully loaded in Node.js/TypeScript/JavaScript

Purpose: ensure slack credentials are loaded into env vars prior to server launch. Here's my env.ts: import dotenv from "dotenv"; import path from "path"; import { loadAwsSecretToEnv } from "./awsSecretLoader"; const st ...

Interactive Bootstrap Card with Popover Effect on Mouse Hover

Let's say I have a Button that contains the popover data toggle: <button type="button" class="btn btn-primary" data-toggle="popover" title="User Info">Popover with Title</button> Here is the JS code ...

Display an image with only a portion visible, no canvas, no frame, and no need

My dilemma involves an img with a surrounding box div. http://jsfiddle.net/6d4yC/7/ 1) I am seeking to display only a portion of the image (250x150) without generating a white overlay when it is in its large size. Placing a #box1 div around the image has ...

Showing the heading again after a new page starts

Currently, I am using WeasyPrint to generate a document and facing an issue with long sections that may span multiple pages. When a section breaks across pages, the name of the section does not display after the page break as intended. The following examp ...

Angular does not always interpret the value returned from a Promise.all call

One of the challenges I'm facing is related to the structure of my controller: controller.things = ['a', 'b', 'c']; controller.loading = true; controller.responses = []; controller.handlePromises = function(){ var pr ...

Enhance local rotation of objects in Three.js

I am working on creating a spaceship-like object with controls, and I have learned that I need to use quaternions to achieve this. To start, I am attempting to make a cube rotate to the left when the A key is pressed. Here is the code I have written for th ...

Are we utilizing this JavaScript function properly for recycling it?

Two functions have been implemented successfully. One function adds the autoplay attribute to a video DOM element if the user is at a specific section on the page. The other function smoothly slides in elements with a transition effect. The only limitatio ...

The Art of Revealing an Element

Is it possible to manipulate a parent div element in JavaScript without affecting its child nodes? For example, transforming this structure: <div class="parent"> <div class="child"> <div class="grandchil ...

Establishing a Connection with Node/Express Routing via JavaScript

When developing a web application using HTML, JavaScript, and Node.js with Express, I often find the need to navigate between pages based on user actions. In HTML, one approach is to add an href link and then set up routes in my app.js file to handle the ...

How can you bypass classList being `undefined` in older browsers?

On modern browsers, the following code works perfectly fine. However, on legacy browsers it throws an error. What is the best way to resolve this issue? Error: TypeError: Result of expression 'document.getElementById("profile").classList' [unde ...

Utilizing the Web Crypto API to implement encryption and decryption in Typescript

Due to security requirements, data cannot be sent in plain-text to the server and credentials should not be visible in the browser's network tab. Hashing could have been used but existing passwords are already stored with hash and salting applied. To ...

Struggling to fetch the last and first name from a document in Firestore using VueJs

https://i.sstatic.net/IdZGi.pngWhen trying to retrieve the last name and first name from a document stored upon signup with a field displayName, I encountered an issue. Despite having a common key as displayName, which should allow me to fetch this informa ...