Skip to content Skip to sidebar Skip to footer

Sum Of Two Input Value By Jquery

I have code : function compute() { if ($('input[name=type]:checked').val() != undefined) { var a = $('input[name=service_price]').val(); var b = $('input[name=m

Solution 1:

Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:

functioncompute() {
    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.

Solution 2:

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.

Solution 3:

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

Solution 4:

use parseInt

var total = parseInt(a) + parseInt(b);


    $('#total_price').val(total);

Solution 5:

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

Post a Comment for "Sum Of Two Input Value By Jquery"