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

Altering the hover functionality for dynamically created class elements

I have a vision to create a unique e-commerce storefront with tile design, featuring an item thumbnail that reveals the item name upon hovering. I found inspiration from this example, but I want the item name to slide up smoothly on hover, rather than simp ...

Tips for aligning two divs of varying sizes side by side

Imagine having two div elements: <div id="container"> <div id="left">line one</div> <div id="right">line one<br/>line two</div> </div> Is there a way to have the left and right divs align at the bottom li ...

What is the process for accessing a particular field in the data returned by the collection.find method in Expressjs and mongodb

I've been attempting to access a specific field returned from the mongodb collection.find method without success. The console.log is not displaying anything. router.get('/buildings', function(req, res, next) { var db = req.db; var collectio ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Is it possible for me to retrieve the error message from my response?

Currently, I am working on displaying backend error messages on the frontend. My approach involves sending a response with an error code and message, then setting a state in my React component to display the error message. While I can successfully display ...

Having trouble finding an element within an HTML DOM that is nested inside an object tag using Selenium

I'm currently in the process of automating tests on an HTML page using Selenium in C#. The parent/outer HTML page has an object tag, within which there is another HTML page. Here's a snippet of how the sample HTML code looks: <!DOCTYPE html&g ...

Switch out div elements for td elements in HTML code

I have written a code snippet that successfully toggles between showing and hiding content. Here is the code: Simple collapsible Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliq ...

Tips for positioning an element at the bottom of a flexible container with variable size

How can I ensure that the Author element in this jsfiddle is aligned properly between the card elements? I am struggling to adjust the size of the details container to match the variable sizes of other elements in the same row. The aim is to have the Auth ...

Learn the best method for accessing and utilizing an existing file effortlessly

As a newcomer to PHP, I have successfully learned how to upload a file from a list using the following code: var file = e.target.files[0]; alert(file); This code returns an [object File], indicating that the file has been uploaded. Now, my question is: ...

Guide on how to retrieve a list of objects from a controller and showcase them utilizing JQuery in a Spring MVC application with ajax functionality

Here is the controller code snippet: @Controller public class MainController { @Autowired SqlSession sqlSession; @Autowired Message messageVO; @RequestMapping(value="getMessages", method=RequestMethod.GET) public @ResponseBody List<Messag ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

NodeJS has a knack for replying even before the function has completed

Struggling with a NodeJS and Express API for a school project. The getAuthUserId function is not working as expected. It decodes the JWT token to retrieve the user Id from the mongoDB server. However, when calling this function in a REST call "/user/authT ...

In the n-th click event, the key press button is fired n times

I am working on developing a game that includes a start button. Once this button is clicked, the game will begin and involves various keyboard key press events. The issue arises when the start button is clicked multiple times causing the game to run repeat ...

Why do my cards keep shrinking instead of moving to a new column when using flexbox and flex-flow?

I'm facing an issue with my flexbox that is causing my items to constantly shrink instead of moving to a new row. I've tried various solutions but nothing seems to work. I have removed the CSS for elements like headers that I believe are unrelate ...

Tips for transferring input field values through the href attribute in HTML?

How can I pass an integer value from a link to an input field's value? Imagine example.com is a webpage with one input field. I would like to achieve something like this: Click here 1 Click here 2 If the user clicks on click here 1, then ...

Enhancing react-to-print functionality for optimal performance across various browsers and mobile platforms

Currently, I am developing a sample react-to-print resume template to be included in a larger portfolio website. While testing the page on Chrome and Edge browsers on a laptop, everything seems optimized. However, there are issues when using Firefox; the b ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

Variations in key-codes between Android Nexus and Samsung mobile devices

As I work on developing a "Pin Code Entry" functionality for an Ionic app, I encounter challenges with different key-codes on various Android devices. The goal is to create a login feature where users input digits into 5 fields using a Numeric keyboard. Th ...