我有一个函数,我正在尝试将已勾选的复选框总数添加到已在文本框中显示的值。我已经工作的解决方案,但如果我取消选中框并再次单击总计,则无法正确更新。
有没有办法可以解决这个问题,以便文本框相应更新?
HTML
<td><input type="text" name="Yeses" id="NumberofRisks" class = "form-control" value ="<?php echo $row['Total-Score'];?> " style = "width:50px"></td>
的Javascript
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = sumField.value;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
答案 0 :(得分:0)
每次调用function sum()
后,您都在更新输入值。
取而代之的是初始sum
值。
然后每次使用此值。
var initial = $("#NumberofRisks").val();
function sum()
{
$("#NumberofRisks").val(initial + $("input[name^='yanswer']:checked").length);
displayRating($("#NumberofRisks").val());
}
答案 1 :(得分:0)
将文本框的原始值保留在变量中。在复选框中添加一个事件侦听器,用于计算复选框的数量,并将该数字添加到原始值,然后更新文本框。
这样的事情:
HTML:
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="textbox" class="text" />
JS:
//Store the original value. The 5 here should be whatever was supposed to be in the textbox.
var originalValue = 5;
$('.text').val(originalValue);
$('.check').on('change', function() {
//Count the number of checked boxes and add it to the original value for display.
var checked = $('.check:checked').length;
$('.text').val(originalValue+checked);
});
这是fiddle。