通过javascript/jquery从html表中获取值并进行计算
getting values from a html table via javascript/jquery and doing a calculation
问题:我有一个html表格,有4列(名称、价格、数量、价值)。"数量"字段有一个输入标记。基本上,有人在数量字段中写入一个数字,然后点击按钮,脚本应该将每行中的价格和数量单元格相乘,并将其写入相应的值单元格。然后,它应该最终添加所有的值,然后将其写在表之后。
看起来很简单,但我无法从javascript/jquery文档中找到它。
这是我的html代码:
<form>
<table border="0" cellspacing="0" cellpadding="2" width="400" id="mineraltable">
<tbody>
<tr>
<td valign="top" width="154">Ore</td>
<td valign="top" width="53">Price Per Unit</td>
<td valign="top" width="93">Quantity</td>
<td valign="top" width="100">Value</td></tr>
<tr>
<td valign="top" width="154"><strong>Arkonor</strong></td>
<td id="11" valign="top" width="53">1</td>
<td valign="top" width="93"><input name="12"></td>
<td id="13" valign="top" width="100"> </td></tr>
//Lots more of these rows... all Price rows have an ID with a 1 at the end, i.e. 21, 31, 41,. ....,
//all the text inputs have a 2 at the end of the name, and all Values have a 3 at the end.
</tbody></table></form>
<p id="result">Your value is: </p>
<button type="button">Calculate</button>
我在这里为您提供了一个关于jsfildde的基本解决方案。
注意,我清理了你的html。
你将不得不做额外的工作来检查无效的输入等,但你应该明白这个想法。
Html:
<table border="0" cellspacing="0" cellpadding="2" width="400" id="mineraltable">
<thead>
<tr>
<td valign="top" width="154">Ore</td>
<td valign="top" width="53">Price Per Unit</td>
<td valign="top" width="93">Quantity</td>
<td valign="top" width="100">Value</td></tr>
<tr>
</thead>
<tbody>
<td valign="top" width="154"><strong>Arkonor</strong></td>
<td class="price" id="11" valign="top" width="53">1</td>
<td class="quantity" valign="top" width="93"><input name="12" value="1"></td>
<td class="value" id="13" valign="top" width="100"> </td>
</tr>
</tbody>
</table>
<p id="result">Your value is: </p>
<button type="button">Calculate</button>
Javascript:
$('button').click(function() {
var total = 0;
$('#mineraltable tbody tr').each(function(index) {
var price = parseInt($(this).find('.price').text());
var quantity = parseInt($(this).find('.quantity input').val());
var value = $(this).find('.value');
var subTotal = price * quantity;
value.text(subTotal);
total = total + subTotal;
});
$('#result').text('Your value is: '+total);
});
相关文章:
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- 如何在自定义指令中获取计算的属性
- 获取唯一值并使用javascript计算金额总和
- 从表单中获取用户输入执行计算(操作顺序)并输出回该表单
- 通过javascript/jquery从html表中获取值并进行计算
- 使用reactjs setState回调获取上一个输入值的计算值
- 正在获取客户端计算机上特定目录中的文件名
- 在 javascript 中逐个类获取元素并计算其中的元素数量
- 以点表示法计算字符串,以从视图中的对象获取相应的值
- 从HTML表单中获取计算得到的JavaScript数据,并将其作为新元素添加到相同的表单操作中以使用PHP保存
- 获取javascript计算字段时遇到问题
- 使用AngularJS从服务器获取计算结果
- 获取计算高度-Javascript-而不是jQuery
- 如何返回外部样式表类应用于元素的所有CSS属性(不获取计算样式!)
- 从两个可观测数组中获取计算值
- 使用Marionette Backbone.js渲染视图后,获取计算的CSS属性(例如:宽度)
- 获取计算的可观察对象依赖项
- 获取计算样式的元素
- 正在游戏控制器中获取计算属性
- 获取计算样式并省略默认值