如何使用 Javascript 或 jQuery 对单选按钮值求和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9796248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sum radio button values using either Javascript or jQuery?
提问by Davinchie_214
Suppose I have 3 radio buttons with different values for each radio button and one textbox which would then display the sum of every radio button that is checked. Which Jquery or Javascript event should I use to sum up the values each time a radio button is clicked?
假设我有 3 个单选按钮,每个单选按钮和一个文本框具有不同的值,然后将显示选中的每个单选按钮的总和。每次单击单选按钮时,我应该使用哪个 Jquery 或 Javascript 事件来汇总值?
Originally, my radio button has a text box next to it for the purpose of displaying the value of the selected radio button but I am having difficulty firing an event to sum up the values from the text boxes that changes by itself(since keyup or keydown wont work on this given situation).
最初,我的单选按钮旁边有一个文本框,用于显示所选单选按钮的值,但我很难触发一个事件来总结来自自身变化的文本框的值(因为 keyup 或 keydown在这种给定的情况下不起作用)。
To better explain what I want to achieve, below is a sample from my work. Any help and tips would be appreciated. Thanks in advance.
为了更好地解释我想要实现的目标,以下是我的工作示例。任何帮助和提示将不胜感激。提前致谢。
P.S.:If it's not to much to ask, can you also add a working sample so I can play around with the working one. Thanks.
PS:如果没有太多要求,您能否也添加一个工作样本,以便我可以玩弄工作样本。谢谢。
Yes
<input type="radio" name="radio1" value="10" />
No
<input type="radio" name="radio1" value="0" /><br />
Yes
<input type="radio" name="radio2" value="10" />
No
<input type="radio" name="radio2" value="0" /><br />
Yes
<input type="radio" name="radio3" value="10" />
No
<input type="radio" name="radio3" value="0" /><br />
Total Score:
<input type="text" name="sum" />
回答by Neysor
I would do it like that:
我会这样做:
function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
score+=parseInt($(this).val(),10);
});
$("input[name=sum]").val(score)
}
$().ready(function(){
$(".calc").change(function(){
calcscore()
});
});
See this js fiddle example
看这个js小提琴示例
the html structure is equal to yours, only i added a class calc
, so that i can selected them easier.
html 结构与您的相同,只是我添加了一个类calc
,以便我可以更轻松地选择它们。
回答by Diego
Assume radio buttons are inside a form with id='myForm', and textbox has id='totalScore' then:
假设单选按钮在一个带有 id='myForm' 的表单中,并且文本框有 id='totalScore' 那么:
var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function (i, e){sum+=$(e).val();});
$("#totalScore").val(sum);