Sum of two input value by jquery

2019-01-14 21:27发布

I have code :

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

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 and modem_price=4000 in this example total input value must be 6000 but it is 20004000

7条回答
Emotional °昔
2楼-- · 2019-01-14 21:33

<script>
$(document).ready(function(){
var a =parseInt($("#a").val());
var b =parseInt($("#b").val());
$("#submit").on("click",function(){
var sum = a + b;
alert(sum);
});
});
</script>

查看更多
做个烂人
3楼-- · 2019-01-14 21:34

use parseInt as a = parseInt($('input[name=service_price]').val())

查看更多
淡お忘
4楼-- · 2019-01-14 21:39

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

and this should work.

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.

查看更多
萌系小妹纸
5楼-- · 2019-01-14 21:47

Because at least one value is a string the + operator is being interpreted as a string concatenation operator. The simplest fix for this is to indicate that you intend for the values to be interpreted as numbers.

var total = +a + +b;

and

$('#total_price').val(+a + +b);

Or, better, just pull them out as numbers to begin with:

var a = +$('input[name=service_price]').val();
var b = +$('input[name=modem_price]').val();
var total = a+b;
$('#total_price').val(a+b);

See Mozilla's Unary + documentation.

Note that this is only a good idea if you know the value is going to be a number anyway. If this is user input you must be more careful and probably want to use parseInt and other validation as other answers suggest.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-14 21:52

Cast them to a Number

$('#total_price').val(Number(a)+Number(b));

But before you do that

if (!isNaN($('input[name=service_price]').val()) {...
查看更多
Fickle 薄情
7楼-- · 2019-01-14 21:54

if in multiple class you want to change additional operation in perticular class that show in below example

$('.like').click(function(){    
var like= $(this).text();
$(this).text(+like + +1);
});
查看更多
登录 后发表回答