jQuery Sum & Subtract Two Input Fields Values

In this tutorial I will explain how to add & subtract two input fields values using jQuery. This is very simple tutorial, you just need to write HTML and jQuery to achieve it.
Note: Don’t forget to include the jQuery library in the header or footer of web page.
The HTML
<form name="form">
<table>
<tr>
<td>Num 1:</td>
<td><input type="text" name="num1" id="num1" /></td>
</tr>
<tr>
<td>Num 2:</td>
<td><input type="text" name="num2" id="num2" /></td>
</tr>
<tr>
<td>Sum:</td>
<td><input type="text" name="sum" id="sum" readonly /></td>
</tr>
<tr>
<td>Subtract:</td>
<td><input type="text" name="subt" id="subt" readonly /></td>
</tr>
</table>
</form>
As you can see above we will add Num 1 and Num 2 and display their result on Sum, and subtract Num 2 from Num 1.
The jQuery
$(function() {
$("#num1, #num2").on("keydown keyup", sum);
function sum() {
$("#sum").val(Number($("#num1").val()) + Number($("#num2").val()));
$("#subt").val(Number($("#num1").val()) - Number($("#num2").val()));
}
});
If you find this tutorial helpful so share it with your friends and leave your comment.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
I display mysql table data using php. I search but find solution for column but not for row. Below I try to show what I want…
<td id="”>
Difference from previous row.
Dear Pankaj,
I am not able to understand your query, what is the relation of your query with this tutorial.
what are the jquery ibraries how to add them
Download tutorial file, jQuery library file is available there. You can also get it from Google. It is free library available on internet.
Why in my form its showing rounding off
$(function() {
$(“#fparkingamount, #ftollamount”).on(“keydown keyup”, sum);
function sum() {
$(“#ftotclaimamount”).val(Number($(“#fparkingamount”).val()) + Number($(“#ftollamount”).val()));
}
});
fparkingamount 8.20
ftollamount 2.20
ftotclaimamount 10.399999?
Well i checked it is showing 10.399999999999999 if i enter the same value as you mentioned above.
If you want to get the round value then you can use.
(10.399999999999999).toFixed(2);
It will give you 10.39
How to sum array id [] ?
Nice logic….
Thanks Shadab,
Wow i used this and it is working @ thank you so much , i have used to subtract to input number and the result gives me NaN but this working Thanks