如何使用Javascript或jQuery来计算单选按钮值? [英] How to sum radio button values using either Javascript or jQuery?

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

问题描述

假设我有3个单选按钮具有不同的值,每个单选按钮和一个文本框,然后显示每个单选按钮的总和检查。每次单击按钮时,应该使用哪个Jquery或Javascript事件来总结值?



最初,我的单选按钮旁边有一个文本框,用于显示所选单选按钮的值,但是我无法点击事件来总结文本框中自动更改的值(由于keyup或keydown不会在此给定情况下工作)。



为了更好地解释我想要实现的,下面是我工作中的一个例子。任何帮助和提示将不胜感激。感谢提前。



PS:如果不是太多问题,还可以添加一个工作示例,以便我可以玩工作一个谢谢。

 
< input type =radioname =radio1value =10 >

< input type =radioname =radio1value =0/>< br />

< input type =radioname =radio2value =10/>

< input type =radioname =radio2value =0/>< br />

< input type =radioname =radio3value =10/>

< input type =radioname =radio3value =0/>< br />
总分:
< input type =textname =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 ,所以我可以选择它们更容易。


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?

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

解决方案

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

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

这篇关于如何使用Javascript或jQuery来计算单选按钮值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆