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
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.
The jQuery$(function() { $("#num1, #num2"). on("keydown keyup", sum); function sum() { $("#sum"). val(Number($("#num1"). val()) + Number($("#num2").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With