如何使用 Javascript 或 jQuery 对单选按钮值求和?

How to sum radio button values using either Javascript or jQuery?(如何使用 Javascript 或 jQuery 对单选按钮值求和?)

本文介绍了如何使用 Javascript 或 jQuery 对单选按钮值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 3 个单选按钮,每个单选按钮都有不同的值,还有一个文本框会显示每个选中的单选按钮的总和.每次单击单选按钮时,我应该使用哪个 Jquery 或 Javascript 事件来汇总值?

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?

最初,我的单选按钮旁边有一个文本框,用于显示所选单选按钮的值,但我很难触发事件来总结文本框中自行更改的值(因为keyup 或 keydown 在这种给定的情况下不起作用).

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).

为了更好地解释我想要实现的目标,以下是我的工作示例.任何帮助和提示将不胜感激.提前致谢.

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.:如果问的不多,您能否也添加一个工作示例,以便我可以使用工作示例.谢谢.

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.

 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" />

推荐答案

我会这样:

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()
    });
});

查看这个 js fiddle 示例

html结构和你的一样,只是我添加了一个类calc,这样我可以更容易地选择它们.

the html structure is equal to yours, only i added a class calc, so that i can selected them easier.

这篇关于如何使用 Javascript 或 jQuery 对单选按钮值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用 Javascript 或 jQuery 对单选按钮值求和?

基础教程推荐