dsfs5420 2017-11-16 04:26 采纳率: 100%
浏览 53
已采纳

如何在javascript中对每个值的输入求和?

I would like to have the sum of the values of each checked checkbox input. I tried my best and have problems with the following code:

$("#timediff").on("keyup", function() {

    var v_id = Number("0"); 

    $("input:checked").each(function () { 
      v_id = Number(v_id) +Number($("input:checked").val());

    alert(v_id);
    });

    var s_id = $("#timediff").val();

    if (s_id<=v_id) {
       alert('The"' + s_id +' h" are smaller than "' + v_id + 'h"');
    }else{
          alert('The"' + s_id +' h" are bigger than "' + v_id + 'h"');
    }
  });

My output is always the sum of the repeated value of the first "checked" checkbox.

For example, Checkbox1: Value="5", Checkbox2: Value="2", Checkbox3: Value="1". The output is 15. But I would like to have 8 as the result. Thank you very much for your help.

  • 写回答

1条回答 默认 最新

  • dragon8899 2017-11-16 04:29
    关注

    Change this:

    $("input:checked").val()
    

    to this:

    $(this).val()
    

    And don't forget to convert s_id to a number before the <= comparison.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料