This snippet can be used to do Real time arithmetic using JavaScript.
In the example below. I am using a simple arithmetic to calculate 4% tax and output real-time total amount.
- Create an HTML form field for input amount. Create two input fields to output tax and total sum in Real time.
0
1
2
3
4
|
<input id=“amount” type=“text” onKeyPress=“OgKeyPress()” onKeyUp=“OgKeyPress()”><br>
<input id=“tax” type=“text” disabled><br>
<input id=“totalamount” type=“text” disabled>
|
2. Following JavaScript code block will be used to calculate tax.
0
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<script>
function OgKeyPress() {
var amount = document.getElementById(“amount”);
var s = amount.value;
var tax = document.getElementById(“tax”);
tax.value = Number(s) * (4/100);
var totalamount = document.getElementById(“totalamount”);
totalamount.value = Number(s) + Number(s * (4/100));
}
</script>
|
So, final snippet will be following:–
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<html>
<body>
<input id=“amount” type=“text” onKeyPress=“OgKeyPress()” onKeyUp=“OgKeyPress()”><br>
<input id=“tax” type=“text” disabled><br>
<input id=“totalamount” type=“text” disabled>
<script>
function OgKeyPress() {
var amount = document.getElementById(“amount”);
var s = amount.value;
var tax = document.getElementById(“tax”);
tax.value = Number(s) * (4/100);
var totalamount = document.getElementById(“totalamount”);
totalamount.value = Number(s) + Number(s * (4/100));
}
</script>
<body>
</html>
|