jQuery sum 复选框值 [英] jQuery sum checkbox values

查看:19
本文介绍了jQuery sum 复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算所有复选框的总和并根据此处的选择更新总计是 html:

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">

这是脚本

   $('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);

    });

如果两者都检查它工作正常,但只有一个检查返回 NaN,将会有更多的复选框,而不仅仅是这两个

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

推荐答案

您只需要考虑检查的项目来计算总数.为此,您只能定位被检查的元素并遍历每个循环以添加它们的值以计算总和.以下示例不涉及单个元素的硬编码.

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);

});

示例:https://jsfiddle.net/8p3ftmuh/2/

这篇关于jQuery sum 复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆