jQuery Sum & Subtract Two Input Fields Values

Demo Download

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

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
  1. 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.

  2. 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?

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *