Hi there

Having trouble calculating the final cost of choices made by a user. I have 4 radio buttons and 2 checkboxes. The first three radio buttons are, all intensive purposes, chocolates with the last radio button stating that the user doesn't want any of the chocolates. The two checkboxes are a milkshake and candyfloss respectively.

The user may only choose one of the three chocolates and optionally the milkshake, candyfloss or both.

What I have so far is as follows:

Javascript code

function calc(sec,val,item)
{
	
	if(!item) { 
		var item = null;
	}

	
	switch(sec)
	{
	
	case 1:
	
		some code for a different function.
		
	break
	
	case 2:
		
		cValue = parseInt(document.getElementById("purchaseTotal").value);
	
		if(item.checked){
			document.getElementById("purchaseTotal").value = cValue+val;
		}else{
			document.getElementById("purchaseTotal").value = cValue-val;	
		}
	
	break;
        }
}

html

<td>Chocolate 1: ZAR 5.00</td>
<td><input name="chocolate" type="radio" id="chocolate" value="" onClick="calc(2,5.00, this);">
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Chocolate 2: ZAR 5.00</td>
<td><input name="chocolate" type="radio" id="chocolate" value="" onClick="calc(2,5.00, this);">
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Chocolate 3: ZAR 1 200.00</td>
<td><input name="chocolate" type="radio" id="chocolate" value="" onClick="calc(2,5.00, this);">
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>I do not wish to buy a chocolate.</td>
<td><input name="chocolate" type="radio" id="chocolate" value="" onClick="calc(2,0, this);">
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Milkshake: ZAR 13.00</td>
<td><input type="checkbox" name="milkshake" id="milkshake" value="" onClick="calc(2,13.00, this);"></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Candyfloss: ZAR 8.00</td>
<td><input type="checkbox" name="candyfloss" id="candyfloss" value="" onClick="calc(2,8.00, this);"></td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="3" align="right" valign="top">Total ZAR  <input name="purchaseTotal" type="text" id="purchaseTotal" value="0"></td>

What happens at the moment is that clicking on one radio button doesn't subtract the amount from the previous selected radio button and clicking on the same radio button just keeps adding its value to the total. I'd like it to do the opposite and not add to the total if clicked repeatedly and if another radio button is selected the amount of the previous radio button must be deducted from the total.

Dani AI

Generated

The behavior seen in this thread is a classic sign of maintaining the total by increment/decrement from click handlers instead of computing the total from the form state. found a working hack, but it becomes fragile quickly (repeated clicks, rounding, and switching radios are common failure points).

A more robust pattern: keep a single source of truth and recompute the total on every input change. Store each input's price in a data- attribute (prefer cents as integers to avoid floating-point surprises), listen for the change event on the containing form (event delegation keeps code small), then sum the prices of checked controls. This eliminates any need to track which radio was previously selected or to guard against repeated clicks.

Example implementation (attach to your form and use data-price in cents):

document.getElementById('orderForm').addEventListener('change', function () {
  const inputs = this.querySelectorAll('input[data-price]');
  let totalCents = 0;
  inputs.forEach(i => {
    if ((i.type === 'radio' || i.type === 'checkbox') && i.checked) {
      totalCents += Number(i.dataset.price);
    }
  });
  document.getElementById('purchaseTotal').value = (totalCents / 100).toFixed(2);
});

Practical notes: give radios the same name and unique ids, use change (better for keyboard users), prefer integers for currency math then format with toFixed(2) or toLocaleString, and make the total field readonly or render it as plain text. This approach replaces brittle conditionals with a clean, testable recalculation that directly fixes the repeated-add and previous-selection problems mentioned above.

I managed to solve my own problem although it isn't the most elegant method. Code is below:

function calc(sec,val,item)
{
	
	if(!item) { 
		var item = null;
	}

	
	switch(sec)
	{
	
	case 1:
	
		some code for a different function.
		
	break
	
	case 2:
		
		cValue = parseInt(document.getElementById("purchaseTotal").value);
	
		if(item.checked){
			document.getElementById("purchaseTotal").value = cValue+val;
		}else{
			document.getElementById("purchaseTotal").value = cValue-val;	
		}
	
	break;
        
        case 3:
		
		cValue = parseInt(document.getElementById("confRegFeeT").value);
	
		if(item.checked){
			if(val==5){
				if((cValue>=5) || (cValue>=26)){
					document.getElementById("confRegFeeT").value = cValue;
				}else{
					document.getElementById("confRegFeeT").value = cValue+val;
				}
			}else if(val==0){
				if(cValue<=21){
					document.getElementById("confRegFeeT").value = cValue;
				}else{
					document.getElementById("confRegFeeT").value = cValue-5;
				}
			}else{
				document.getElementById("confRegFeeT").value = cValue;
			}
		}
	
	break;
        }
}

In my html I changed the onclick for the radio buttons to calc(3,5,this)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.