jQuery sum checkbox values

南楼画角 提交于 2020-01-22 03:40:26

问题


I'd need to calculate sum of all checkboxes and update total based on selection here is html:

<input type="checkbox" id="basic_single" name="basic_single" value="400">
<input type="checkbox" id="basic_double" name="basic_double" value="680">
.
.
.
<input type="text" name="total" value="" size="30" id="total">

here is the script

   $('input:checkbox').change(function ()
     {
      var total = 0;
      var basic_single = parseInt($('#basic_single:checked').val());
      var basic_double = parseInt($('#basic_double:checked').val());

      var total = basic_single + basic_double;

      $("#total").val(total);

    });

if both are checked it works fine, but just one checked returns NaN, there will be more checkboxes than just these two


回答1:


You need to consider only the items which are checked to calculate the total. For this, you can only target the elements which are checked and iterate through each loop to add their values to calculate the sum. Following example involves no hardcoding of individual elements.

$('input:checkbox').change(function ()
{
      var total = 0;
      $('input:checkbox:checked').each(function(){ // iterate through each checked element.
        total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
      });     
      $("#total").val(total);

});

Example : https://jsfiddle.net/8p3ftmuh/2/




回答2:


You can use .not() to exclude #total element value from calculations, .get() , Array.prototype.reduce() , + operator to cast value of :checkbox to Number

$(":checkbox").change(function(event) {
  $("#total").val(function() {
    return $(event.target.tagName).not("[type=text]")
    .get().reduce(function(a, b) {
        return +a.value + +b.value
    })
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="checkbox" id="basic_single" name="basic_single" value="400">
<input type="checkbox" id="basic_double" name="basic_double" value="680">
<input type="text" name="total" value="" size="30" id="total">


来源:https://stackoverflow.com/questions/36136351/jquery-sum-checkbox-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!