如何对两个输入字段求和 [英] How to sum two input fields

查看:194
本文介绍了如何对两个输入字段求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html表中具有以下布局:

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>

表行数据是从mysql数据库中获取的,第5行除外(项目:其他).页面加载时,"Total"的值也从mysql数据库中获取.如果用户将任何值添加到其他"行,则每次总计"的值都应将用户输入值与总计"行的值相加.

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.

我正在尝试通过以下jquery代码来做到这一点:

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);
});
});

但是,它不是将两个值相加,而是将输入值相加. i,g:如果total为5,000且用户输入50,则无法将total计为5050,而是将total value更改为505000.我认为这两个字段中的任何一个都被jquery评估为文本而不是数字.

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.

什么是正确的代码?

推荐答案

,您需要先分析这些文本框的值,然后再添加它们.您还需要修改输入元素选择器. ta是元素的ID.您应该使用id选择器(#):

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(#):

$("#ta").keyup(function(){
var vat = parseInt($(this).val());
var total = parseInt($("#tp").val());
    total = vat+total;
$("#tp").val(total);
});

这篇关于如何对两个输入字段求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆