Take a look at this table:
<table cellpadding="0" cellspacing="0" class="order_form">
<tr>
<th>Amount</th>
<th>Desc</th>
<th>Price</th>
<th>To开发者_StackOverflow中文版tal</th>
</tr>
<tr>
<td><input type="text" class="order_count" /></td>
<td>
<span class="order_desc">Middagstallerken</span>
</td>
<td>
<span class="order_price">1,15</span>
</td>
<td>
<span class="order_each_total"></span>
</td>
</tr>
[...]
</table>
Upon entering amount I need to select the class "order_price" and multiply it with the value of the input "order_count" and place it in "order_each_count". I have a lot of these rows so I need to find the next class in the row.
I have tried using some function like this but without result:
<script type="text/javascript">
$(document).ready(function(){
$('.order_count').keyup(function() {
var each_price = $(this).prevUntil("tr").find("span.order_price").text();
});
});
</script>
I hope someone have a good solution :-)
Use closest()
instead of prevUntil
:
$(document).ready(function(){
$('.order_count').keyup(function() {
var amount = parseInt($(this).val(), 10);
var each_price = $(this)
.closest('tr')
.find('span.order_price')
.text()
.replace(',', '.'); // Floats use . as separator
each_price = parseFloat(each_price);
total_price = amount * each_price;
// Update the value
$(this)
.closest('tr')
.find('span.order_each_total')
.text(total_price
.toFixed(2) // "Round" to two decimal places
.replace('.', ',') // Format properly
);
});
});
Remember to use parseFloat
or parseInt
when trying to use numbers from DOM in calculations – they're strings as default.
精彩评论