我有一个小脚本,用于检查选定的框并将其广告出来。
有些盒子值两个,有些则值一个。
我可以让它们相加,但前提是我首先选择两个指针之一,反之亦然。
HTML
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">Some blah blah text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="two">Text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">text</label>
</div>
Javascript
$(".two").change(function() {
var classes = $("input[type='checkbox'].two:checked").map(function() {
return this.className;
}).get().length * 2;
document.getElementById("program_management2").innerHTML = " Score:" + " " + Math.floor(classes) ;
$(".one").change(function() {
var classes2 = $("input[type='checkbox'].one:checked").map(function() {
return this.className;
}).get().length;
document.getElementById("program_management").innerHTML = " Score:" + " " + Math.floor(classes2 + classes) ;
});
});
最佳答案
如果您只想添加每个选中复选框的值,则应使用 value
属性。
由于该值是一个字符串,因此您必须将其解析为整数才能在加法中使用它。
$("input[type='checkbox']").click(function(){
var result = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1">This box value is 1<br>
<input type="checkbox" value="2">This box value is 2<br>
<input type="checkbox" value="5">This box value is 5<br>
<br>
<br>
The checked total is: <span id="total">0</span>
编辑
我添加了“已检查类别”计数。
$("input[type='checkbox']").click(function(){
var result = 0;
var classOne = 0;
var classTwo = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
if( $(this).hasClass("one") ){
classOne++;
}
if( $(this).hasClass("two") ){
classTwo++;
}
$("#totalOne").html(classOne);
$("#totalTwo").html(classTwo);
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<br>
<br>
The checked total value is: <span id="total">0</span><br>
Class "one" checked total : <span id="totalOne">0</span><br>
Class "two" checked total : <span id="totalTwo">0</span><br>
关于javascript - 如何让我的结果在 javascript 中正确相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289055/