通过javascript/jquery从html表中获取值并进行计算

getting values from a html table via javascript/jquery and doing a calculation

本文关键字:获取 计算 javascript jquery html 通过      更新时间:2023-09-26

问题:我有一个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">&nbsp;</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">&nbsp;</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);
});​