I have following layout in an html table:
<table>
<tr><td>Id</td><td>Item Name</td><td>Value</td></tr>
<tr><td>1</td><td>Shampoo</td><td>200</td></tr>
<tr><td>2</td><td>Soap</td><td>20</td></tr>
<tr><td>3</td><td>Toothpaste</td><td>8</td></tr>
<tr><td></td><td>Others</td><td><input class="ta" type="text" value="" /></td></tr>
<tr><td></td><td>Total</td><td><input id="tp" type="text" value="228" /></td></tr>
</table>
Data of table rows are fetched from mysql database except 5th row (Item:Others). While page loads, value of "Total" is also fetched from mysql database. If an user put any value to "Others" row, everytime the value of "Total" should sum the user input value + value of "Total" row.
I am trying to do this by the following jquery code:
$(document).ready(function(){
$(".ta").keyup(function(){
var vat = $(this).val();
var total = $("#tp").val();
total = vat+total;
$("#tp").val(total);
});
});
However, it is not doing the sum of two value, instead it is adding the input value. i,g: If total is 5,000 and user input 50, it can't calculate total as 5050, instead it is changing total value as 505000. I think any of these two fields are evaluating as text instead digit by jquery.
What should be the right code?
You are using
class
selector instead useid
selector(because there is no element with classta
in your HTML structure) and useparseInt()
as shown :-try
You need to store the value of
total
in a variable else you will loose the original value.Also to add the values of textfields(which are strings), you need to convert them to int(using unary plus or parseInt())
you need to parse those textboxes values before adding them. you will also need to modify the input element selector.
ta
is id of element. you should use id selector(#
):use psrseInt javascript function