如何在javascript中对每个值的输入求和?
问题描述:
I would like to have the sum of the values of each checked checkbox input. I tried my best and have problems with the following code:
$("#timediff").on("keyup", function() {
var v_id = Number("0");
$("input:checked").each(function () {
v_id = Number(v_id) +Number($("input:checked").val());
alert(v_id);
});
var s_id = $("#timediff").val();
if (s_id<=v_id) {
alert('The"' + s_id +' h" are smaller than "' + v_id + 'h"');
}else{
alert('The"' + s_id +' h" are bigger than "' + v_id + 'h"');
}
});
My output is always the sum of the repeated value of the first "checked"
checkbox.
For example, Checkbox1: Value="5", Checkbox2: Value="2", Checkbox3: Value="1"
.
The output is 15.
But I would like to have 8 as the result. Thank you very much for your help.
答
Change this:
$("input:checked").val()
to this:
$(this).val()
And don't forget to convert s_id
to a number before the <=
comparison.