jquery的两个输入值的总和 [英] Sum of two input value by jquery
问题描述
我有代码:
function compute() {
if ($('input[name=type]:checked').val() != undefined) {
var a = $('input[name=service_price]').val();
var b = $('input[name=modem_price]').val();
var total = a + b;
$('#total_price').val(a + b);
}
}
在我的代码中我想要两个文本输入的和值并写入id为total的文本输入
In my code I want sum values of two text inputs and write in a text input that has an id of "total"
例如,我的两个数字不能相加:
My two numbers don't sum together for example :
service_price value = 2000
和 modem_price = 4000
此示例中的
总输入值必须是6000但是它是20004000
service_price value = 2000
and modem_price=4000
in this example total input value must be 6000 but it is 20004000
推荐答案
您的代码是正确的,除了您添加(连接)字符串,而不是添加整数。只需将您的代码更改为:
Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:
function compute() {
if ( $('input[name=type]:checked').val() != undefined ) {
var a = parseInt($('input[name=service_price]').val());
var b = parseInt($('input[name=modem_price]').val());
var total = a+b;
$('#total_price').val(a+b);
}
}
这应该有效。
这是一个工作示例,当复选框上的值复选时更新总和(如果选中此项,则在更改其中一个字段时也会更新值): jsfiddle 。
Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.
这篇关于jquery的两个输入值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!