【问题标题】:How do I get the sum based on selected radio button only?如何仅根据选定的单选按钮获得总和?
【发布时间】:2020-08-22 08:29:37
【问题描述】:

我有一个表格,我想在其中收集我的输出 此表单显示在表格中,每行有 2 个选项可供选择 我的代码的问题是两个按钮加起来,但我需要添加其中一个

这是我的代码:

<script type="text/javascript">

  $(document).on("change", ".qty1", function() {
      var sum = 0;
      $(".qty1").each(function(){
          sum += +$(this).val();
      });
      $(".total").val(sum);
  });

</script>

<table>
  <tr>
    <td><input class="qty1" type="radio" name="product_1" value="123" /></td>
    <td><input class="qty1" type="radio" name="product_1" value="234" /></td>
  </tr>
  <tr>
    <td><input class="qty1" type="radio" name="product_2" value="123" /></td>
    <td><input class="qty1" type="radio" name="product_2" value="234" /></td>
  </tr>  
</table>

<input class="total" type="text" name="" value="">

【问题讨论】:

  • "我的代码的问题是两个按钮加起来,但我需要添加其中一个"如何决定从每一行添加哪一个?
  • @palaѕн 从他们的名字 att
  • 但是每一行有两个同名的元素。
  • @palaѕн 如何分隔行?用id可以吗?
  • 每一行是一个产品,价格是两个包装。我放了相同的名字让用户只选择其中一个

标签: jquery input sum radio-button


【解决方案1】:

要获得基于所选单选按钮的总和,您可以简单地循环通过 checked 单选按钮,而不是循环通过类 .qty1 的所有元素,例如:

$(document).on("change", ".qty1", function() {
  var sum = 0;
  $(".qty1:checked").each(function() {
    sum += +$(this).val();
  });
  $(".total").val(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input class="qty1" type="radio" name="product_1" value="123" />123</td>
    <td><input class="qty1" type="radio" name="product_1" value="234" />234</td>
  </tr>
  <tr>
    <td><input class="qty1" type="radio" name="product_2" value="123" />123</td>
    <td><input class="qty1" type="radio" name="product_2" value="234" />234</td>
  </tr>
</table>

<input class="total" type="text" name="" value="">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-19
    • 2021-04-14
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2018-07-24
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多