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

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

问题描述

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

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总和复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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