Reputation: 4050
Problem: I have a html table with 4 columns (Name, Price, Quantity, Value). The Quantity field has an input tag. Basically someone writes the a number in the quantity field and then hits a button and the script should multiply the Price and Quantity cell in each row and write it in the respective value cell. Then it should finally add all the Values and then write it after the table.
Seems simple enough but I can't figure it out from the javascript / jquery documentation.
this is my html code:
<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>
Upvotes: 0
Views: 3762
Reputation: 12448
I have done a basic solution for you on jsfildde here.
Note I cleaned up your html a bit.
And you will have to do additional work to check for invalid inputs etc. but you should get the idea.
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);
});
Upvotes: 2