Как получить сумму только на основе выбранного переключателя? - PullRequest
1 голос
/ 07 мая 2020

У меня есть форма, в которой я хочу собрать свой вывод. Эта форма отображается в таблице, где есть 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="">

1 Ответ

0 голосов
/ 07 мая 2020

Чтобы получить сумму на основе выбранного переключателя, вы можете просто l oop с помощью переключателей 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="">
...