当我检查它们时,我有一个复选框列表我得到了值,然后我想将它们添加起来但我似乎无法让我了解它。
示例 http://jsfiddle.net/zidski/w3mwkkh3/
$('body').on('click' , '.done' , function() {
var selectedCheckboxValue = "";
$('input.checkbox:checked').each(function() {
selectedCheckboxValue += $(this).val();
});
$('.filter-selected-count').text(selectedCheckboxValue);
});
答案 0 :(得分:5)
您应该将代码替换为此
var selectedCheckboxValue = 0;
$('input.checkbox:checked').each(function() {
selectedCheckboxValue += parseInt($(this).val());
});
看到这里工作正常
答案 1 :(得分:3)
要对所选复选框的值求和,您可以获取值,但首先将它们转换为整数,如:
$('body').on('click', '.done', function() {
//declare a variable to sum the values of checked checkboxes
var sum = 0;
$('input.checkbox:checked').each(function() {
//you can first convert to int before sum them
sum += ~~$(this).val();
});
//add the result
$('.filter-selected-count').text(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<label>
<input id="checkbox1" class="checkbox" type="checkbox" name="rooms" value="2" />Rooms (2)</label>
</li>
<li>
<label>
<input class="checkbox" type="checkbox" name="bathroom" value="2" />Bathroom (2)</label>
</li>
<li>
<label>
<input class="checkbox" type="checkbox" name="view" value="2" />View from room (2)</label>
</li>
<li>
<label>
<input class="checkbox" type="checkbox" name="dining" value="2" />Dining (2)</label>
</li>
<li>
<label>
<input class="checkbox" type="checkbox" name="grounds" value="2" />Hotel & grounds (2)</label>
</li>
<li>
<label>
<input class="checkbox" type="checkbox" name="localarea" value="2" />Local area (2)</label>
</li>
</ul>
<button class="done">Done</button>
<br />Count: <span class="filter-selected-count"></span>