Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of two input value by jquery

Tags:

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

like image 386
Ebad ghafoory Avatar asked Jul 01 '11 20:07

Ebad ghafoory


People also ask

How do you auto calculate sum of input values using jquery?

Required Steps to get the sum of input values using JqueryDeclare all the input fields with the id attributes of each input field to find the desired values in each row. Also declare the input fields with the class attributes of each input field to collect the sum of all the desired fields.

How to add and subtract in jQuery?

The jQuery$(function() { $("#num1, #num2"). on("keydown keyup", sum); function sum() { $("#sum"). val(Number($("#num1"). val()) + Number($("#num2").


1 Answers

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.

like image 61
Tadeck Avatar answered Oct 03 '22 20:10

Tadeck