如何仅根据选定的单选按钮获取总和?
How do I get the sum based on selected radio button only?
我有一个表格,我想在其中收集我的输出
此表单显示在 table 中,其中每行有 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="">
要获得基于所选单选按钮的总和,您可以简单地遍历 checked
单选按钮,而不是使用 class .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="">
我有一个表格,我想在其中收集我的输出 此表单显示在 table 中,其中每行有 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="">
要获得基于所选单选按钮的总和,您可以简单地遍历 checked
单选按钮,而不是使用 class .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="">