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 开发者_JS百科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 change
event, there's already a checked radio (you don't know previous state). You could store this state in an auxiliar var, like this:
var $checked; //This is the aux var that saves previous state
$(document).ready(function(){
$checked = $(":radio[name='timescale']:checked");
});
function changePrice(t){
v = parseInt($(t).val());
s = $("#subtotal");
x = parseInt(s.text());
if($checked.size() > 0){
s.text(x);
} else {
s.text(x + v);
}
$checked = $(this);
}
Hope this helps. Cheers
精彩评论