The Radio button and Checkbox values are causing an issue where the Radio button is continuously summing upon clicking without a limit. Why is this happening? Check out

I'm currently stuck in a function and believe it would be helpful for you to guide me along the correct path.

My goal is to sum the values of checked boxes with the values of checked radio buttons. However, the radio values are continuously accumulating on each click, indicating an issue with the function. Nonetheless, as someone who enjoys delving into code and learning independently, I am determined to resolve this.

The total sum displays the correct values, but upon clicking a radio button again, it accumulates once more.

I have provided a snippet for you to test out. Your assistance would be greatly appreciated!

html, body {
    height: 100%;
    margin: 0;
}
#left {
    width: 20%;
    height: 100%;
    position: fixed;
    outline: 1px solid transparent;
    background: white;
}
#right {
    width: 80%;
    height: auto;
    outline: 1px solid transparent;
    position: absolute;
    right: 0;
    background: #FFFFFF;
}
   
.text{ 
width:250px; 
height:286px; 
background:#FFF; 
opacity:0;
}
.checkbox-custom, .radio-custom {
    opacity: 0;
    position: absolute;   
}
.checkbox-custom, .checkbox-custom-label, .radio-custom, .radio-custom-label {
    display: inline-block;
    vertical-align: middle;
    margin: 5px;
    cursor: pointer;
}
.checkbox-custom-label, .radio-custom-label {
    position: relative;
}
.checkbox-custom + .checkbox-custom-label:before, .radio-custom + .radio-custom-label:before {
    content: '';
    background: #fff;
    border: 2px solid #ddd;
    display: inline-block;
    vertical-align: middle;
    width: 20px;
    height: 20px;
    padding: 2px;
    margin-right: 10px;
    text-align: left;
}
.checkbox-custom:checked + .checkbox-custom-label:before {
    background: rebeccapurple;
}
.radio-custom + .radio-custom-label:before {
    border-radius: 50%;
}

.radio-custom:checked + .radio-custom-label:before {
    background: rebeccapurple;
}

.checkbox-custom:focus + .checkbox-custom-label, .radio-custom:focus + .radio-custom-label {
  outline: 1px solid #ddd; /* focus style */
}
.checkbox-grid li {
    display: block;
    float: left;
    width: 25%;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Welcome to Invest Consulting!</title>
<link href="official-site-styles.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    var total = 0;

    function calculate(item){
    
        if(item.checked){
           total += parseInt(item.value);
        }
        else{
           total -= parseInt(item.value);
        }
    
        document.getElementById('Totalcost').innerHTML = total + "";
}

</script>

</head>

<body>

<input id="radio-1" class="radio-custom" name="radio-group" type="radio" value="500" onClick="calculate(this); -500" />
<label for="radio-1" class="radio-custom-label">Service</label>

<input id="radio-2" class="radio-custom" name="radio-group" type="radio" value="500" onClick="calculate(this); -500" />
<label for="radio-2" class="radio-custom-label">Commerce</label>

<input id="radio-3" class="radio-custom" name="radio-group" type="radio" value="500" onClick="calculate(this); -500" />
<label for="radio-3" class="radio-custom-label">Service and Commerce</label>

<br>

<ul class="checkbox-grid">

<li>
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox" value="500" onClick="calculate(this);" />
<label for="checkbox-1" class="checkbox-custom-label">$500</label>
</li> 

(remaining HTML snippet omitted for brevity)

Answer â„–1

Revise your code to include the following changes

<script type="text/javascript">

var totalAmount = 0;
var radioTotal = 0;

function updateTotal(item){          

  if (item.type === 'radio') {
    radioTotal = parseInt(item.value);
  } else {
    if(item.checked){
       totalAmount += parseInt(item.value);
    }
    else{
       totalAmount -= parseInt(item.value);
    }
  }      

  document.getElementById('GrandTotal').innerHTML = (totalAmount + radioTotal) + "";
}

</script>

Ensure you maintain separate totals for checkboxes and radio buttons.

Answer â„–2

When you select a radio button, the total value must be reset to zero and all checkboxes must be unchecked. If you wish to keep checkboxes checked when changing the radio selection, set the total to zero before the loop and sum the values of all checked checkboxes within the loop. Here is an example:

html, body {
    height: 100%;
    margin: 0;
}
#left {
    width: 20%;
    height: 100%;
    position: fixed;
    outline: 1px solid transparent;
    background: white;
}
#right {
    width: 80%;
    height: auto;
    outline: 1px solid transparent;
    position: absolute;
    right: 0;
    background: #FFFFFF;
}
   
.text{ 
width:250px; 
height:286px; 
background:#FFF; 
opacity:0;
}

// Other CSS styles omitted for brevity

<p>Some HTML code here</p>

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

Preventing the (click) function from being activated during dragging in Angular 10

My div contains an openlayers map setup as shown below: <div id="map" (click)="getInfo($event)" class="map"></div> Whenever I drag my mouse to move around the map, the getInfo function is triggered. Is there a way to make it trigger only when ...

Using globs to specify files for gulp.src

I'm facing a challenge in setting up a glob array for my JavaScript concatenation build task within the Gulp workflow. The file structure I am working with looks like this: ├── about │ └── about.js ├── assets ├── contact â ...

Having trouble getting SCSS to function properly? (Updated Code)

Transitioning from CSS to SCSS is my current project. I decided to make the switch because of SCSS's nesting capabilities, which I find more convenient for coding. However, I'm facing some challenges getting it to work properly. In my regular CSS ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

When CSS 3 checkbox value is toggled to "off", it returns as null

I am currently using a checkbox element with the following HTML: <div class="onoffswitch"> <input type="checkbox" name="showOnNavigation" class="onoffswitch-checkbox" id="showOnNavigation" checked> <label class="onoffswitch-label" f ...

The onchange event for the input type=file is failing to trigger on Google Chrome and Firefox

Update: Solved: http://jsfiddle.net/TmUmG/230/ Original question: I am facing an issue with handling image/logo upload alongside a hidden input type=file: <form class="image fit" id="theuploadform"> <input title="click me to chan ...

Determine the height of the left div, which is set to auto, and apply the same height to the right div, which has overflow set

I am facing an issue that needs a solution. I need to ensure that two div elements have the same height. The left div should have 'auto' height while the right one must match it. Moreover, the right div contains 14 nested divs that need to be scr ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Issue with javascript code not functioning post axios request

When working on my project, I utilize axios for handling Ajax requests. I crafted a script that attaches a listener to all links and then leverages Axios to make the Ajax request. Following the Ajax request, I aim to execute some post-processing steps. Aft ...

Testing an Express application using Jenkins

After spending hours searching for a way to execute my Mocha unit tests in Jenkins for my Express JS application, I am still struggling to find a solution. While writing the tests themselves is relatively easy, integrating them with my app has proven to b ...

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Update Personal Information with PHP and MySQL

i have two files named edit.php and update.php. The content of edit.php is as follows: <?php session_start(); $_SESSION['id'] = '9'; $id = $_SESSION["id"]; $username = $_POST["username"]; $fname = $_POST["fname"]; $password = $_POST ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

When the cursor is placed over it, a new div is layered on top of an existing

Currently, I am working on a project with thumbnails that animate upon hovering using jQuery. One of the challenges I have encountered is adding a nested div inside the current div being hovered over. This nested div should have a background color with som ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

What is the best way to send multiple responses from an Express server using res.write and execute a specific action after each write operation?

I currently have an active express server that is sending data using res.write() Fetcher.js function fetcher() { console.log("fetcher function called") fetch('/units.html', { method: "POST", body: JSO ...

Inserting lines into the text, creating a visually appealing layout

Can a notepad design be created using CSS only? Is it feasible to include lines between text lines without using underscores? I want it to look like this example but with minimal spacing between lines and no manual insertion of span tags since the text wi ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/two ...