【问题标题】:Add all values with input name="TotalInline[]"添加输入名称=“TotalInline[]”的所有值
【发布时间】:2012-09-04 17:37:59
【问题描述】:

如何从名称为 name="TotalInline[]" 的所有输入中添加值?

以下不接缝工作:

    var total = 0;
    $.each('input[name="TotalInline[]"];,function() {
        total += this;
    });

【问题讨论】:

    标签: javascript jquery arrays jquery-selectors


    【解决方案1】:

    这应该可行:

    var total = 0;
    $('input[name="TotalInline"]').each(function() {
        // assuming you have ints in your inputs, use parseFloat if those are floats
        total += parseInt(this.value, 10); 
    });
    

    【讨论】:

    • 我实际上想用name="SomeName[]" 进行选择,但是在更改HTML 语法之后就足够了!谢谢。
    • 名称中实际上包含[]。你没有那个。
    • 这不是一个有效的名称。见w3.org/TR/html401/types.html#type-name
    • @dystroy - 您链接的规范已过时。 name 属性中绝对欢迎使用括号。这就是你标记数组的方式。
    • @dystroy HTML5 允许,PHP 使用它来自动构建数组。大多数浏览器实际上都允许“无效”字符。
    【解决方案2】:
    var total = 0;
    $.each($('input[name="TotalInline[]"]'), function() {
        total += parseInt(this.value, 10);
    });
    

    【讨论】:

    【解决方案3】:

    你有一些严重的语法错误,试试这个:

    var total = 0;
    $('input[name="TotalInline[]"]').each(function () {
      total += parseInt(this.value, 10);
    });
    

    【讨论】:

      【解决方案4】:

      试试这样...

      var total = 0;
      $('input[name="TotalInline[]"]').each(function() {
              total += parseInt($(this).val(),10);
          });
      

      【讨论】:

      • 虽然我喜欢jQuery,但$(this).val()真的没必要。
      【解决方案5】:
      var total = 0;
      
      $('input[name="TotalInline[]"]').each(function() {
          total += +this.value.replace(/[^\d.]/g, '');
      });
      
      • 使用快速正则表达式仅过滤掉数字(和小数点)。
      • 使用+ 前缀转换为数字。

      【讨论】:

      • + 转换为数字的好技巧!
      猜你喜欢
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 2017-03-27
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2021-08-29
      相关资源
      最近更新 更多