I have radio buttons and groups created dynamically and their values are numeric. Each group has 5 radio buttons all ranging in value. So when any radio button is clicked, I'd like the value to be added to the total in a text field, and when a new radio button in a group is deselected, the old value should be subtracted and the new value added.
Can someone point me in the right directi开发者_Go百科on or share some code if you have it? Thank you!
Rather than subtracting the old value and adding the new value I would just recalculate the total each time. That way you don't have to worry about keeping track of the old value for each group. You can use JQuery to simplify things, but in plain JavaScript something like the following would work to just loop through all radio buttons and add the values of those that are currently checked:
function calculateTotal() {
var x = document.getElementsByTagName("input");
var i,
total = 0;
for(i=0; i < x.length; i++){
if (x[i].type == "radio" && x[i].checked)
total += parseInt(x[i].value,10);
}
// display total somewhere;
}
Either set the onclick
handler for each radio button to call calculateTotal
or set a single onclick
on some parent container.
JQuery is the short answer. You can find lots of examples on google and at jquery.com. Bind to click event of the radiobutton and then do what you have to do.
something like this http://jsfiddle.net/robx/KXEmW/ I gave a simple example of just adding new value. So you just need to do the math to add/subtract what and when.
Using jQuery, if you have an html like this:
<form id="form1">
<input type="radio" name="chk" value="1">
<input type="radio" name="chk" value="2">
<input type="radio" name="chk" value="3">
</form>
<form id="form2">
<input type="radio" name="chk" value="1">
<input type="radio" name="chk" value="2">
<input type="radio" name="chk" value="3">
</form> ...
and somewhere you have...
<input type="text" name="total" value="">
The jQuery to calculate the total would be like:
var form1Val = parseInt($('#form1 input[name$=chk]').val());
var form2Val = parseInt($('#form2 input[name$=chk]').val());
var total = form1Val + form2Val + ...;
$('input[name$=total]').val(total);
You can of course do a loop on each form then total them later.
P.S. Code is not tested
精彩评论