Take the entered value, multiply the contents of the <td> and show the result in another <td> with jQuery
I have an HTML table, each row has several td. One of td contains a number input field.
Now I'm trying to use jQuery to enter the entered number, multiply it by the number inside another td on the same line, and then display the result in another td (the same line), but for now I can not seem to make it work.
Not sure if I missed something simple or I'm completely unfamiliar
Here is my HTML
<table class="my-table">
<thead>
<tr>
<td>Header 1</td>
<td>Header 2</td>
<td>Header 3</td>
<td>Header 4</td>
</tr>
</thead>
<tbody>
<tr data-row-num="1">
<td>Item 1</td>
<td><span class="numerator">10</span> / 1</td>
<td><form><input type="number"></form></td>
<td class="rowtotal">Β£0</td>
</tr>
<tr data-row-num="1">
<td>Item 2</td>
<td><span class="numerator">10</span> / 1</td>
<td><form><input type="number"></form></td>
<td class="rowtotal">Β£0</td>
</tr>
<tr data-row-num="1">
<td>Item 3</td>
<td><span class="numerator">10</span> / 1</td>
<td><form><input type="number"></form></td>
<td class="rowtotal">Β£0</td>
</tr>
</tbody>
</table>
And here is my jQuery for now
//Finds inputted text in table and binds to function calculateSum?
$(function () {
var tbl = $('.my-table');
tbl.find('input[type=number]').bind("keyup", function () {
calculateSum();
});
});
//Finds numerator and multiplies by input, outputs result?
function calculateSum() {
var tbl = $('.my-table');
tbl.find('tr').each(function () {
var numeratorValue = $(this).find('.numerator');
var numerator = numeratorValue.html;
$(this).find('input[type=number]').each(function () {
var result = $(this).val * numerator;
$('.rowtotal').html('Β£' + result);
});
});
}
Any help that is most appreciated Thanks
+4
2 answers
input keyup, . tr, .numerator. input .numerator .rowtotal.
$('input[type=number]').on("input", function () {
var tr = $(this).closest('tr');
var num = this.value;
var numerator = tr.find('.numerator').text();
tr.find('.rowtotal').text('Β£' + num * numerator);
});
$('input[type=number]').on("input", function () {
var tr = $(this).closest('tr');
var num = this.value;
var numerator = tr.find('.numerator').text();
tr.find('.rowtotal').text('Β£' + num * numerator);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="my-table">
<thead>
<tr>
<td>Header 1</td>
<td>Header 2</td>
<td>Header 3</td>
<td>Header 4</td>
</tr>
</thead>
<tbody>
<tr data-row-num="1">
<td>Item 1</td>
<td><span class="numerator">10</span> / 1</td>
<td><form><input type="number"></form></td>
<td class="rowtotal">Β£0</td>
</tr>
<tr data-row-num="1">
<td>Item 2</td>
<td><span class="numerator">10</span> / 1</td>
<td><form><input type="number"></form></td>
<td class="rowtotal">Β£0</td>
</tr>
<tr data-row-num="1">
<td>Item 3</td>
<td><span class="numerator">10</span> / 1</td>
<td><form><input type="number"></form></td>
<td class="rowtotal">Β£0</td>
</tr>
</tbody>
</table>+1