I’m trying to write a jQuery function that changes the subtotal when a radio button is clicked. There will be 3+ radio buttons – each with a different price value that will add onto the existing subtotal.
I only want the subtotal to be updated if there are no existing radio buttons selected (this set of radio buttons – with the same name attribute). This is what I currently have:
HTML:
<input type="radio" value="45" name="timescale" onclick="changePrice(this)">
jQuery:
function changePrice(t){
v = parseInt($(t).val());
s = $("#subtotal");
x = parseInt(s.text());
if($(t).siblings("input").is(":checked")){
s.text(x);
} else {
s.text(x + v);
}
}
I want the if statement to check if the radio button’s siblings are selected. If they are: only replace the subtotal s.html() with its current value. If they aren’t: replace the s.html() with the updated value (which is the current value + the radio button’s value). But at the moment every click updates the subtotal – even if other radio buttons are already selected. Where am I going wrong?
EDIT
The problem is that the moment of the
changeevent, there’s already a checked radio (you don’t know previous state). You could store this state in an auxiliar var, like this:Hope this helps. Cheers