jquery - 如何仅根据选定的单选按钮获得总和?
问题描述
我有一个表格,我想在其中收集我的输出 这个表格显示在一个表格中,每行有 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
单选按钮,而不是循环通过类的所有元素,.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="">
推荐阅读
- django - 如何创建相同模型但不同用户的多个实例
- mysql - 如何在mysql的from子句中使用临时表?
- ios - 构建错误:添加通知服务扩展时找不到“React/RCTBridge.h”文件
- react-native - react native中基于屏幕隐藏材质底部导航
- c - C 启动代码只写汇编混淆
- javascript - 试图找到数组的元素,其中数组左侧的总和等于 JavaScript 中数组右侧的总和
- flutter - 如何在颤动中最小化正在运行的页面
- python - 在python中使用另一个多维数组从多维数组中采样的最简单方法
- c# - 如何在c#中将telerik按钮添加到winform
- android - 使用递归字符串路径将对象列表组织到嵌套数组