I have a jQuery percentage calculator which is showing a result in a heading element. I want to show result in the table cell instead. You can check code below. Please help me.
$(document).on("change keyup blur live", "input", ".change-calculator", e => {
let $td = $(e.currentTarget).closest('td');
let from = Number($td.find('.calc-from').val());
let to = Number($td.find('.calc-to').val());
let result = ((to - from) / from) * 100;
$td.next().find('.calc-result').text(result.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.js"></script>
<table>
<tr>
<th>Calculator 01</th>
<th>Calculator 01 Result</th>
<th>Calculator 02</th>
<th>Calculator 02 Result</th>
</tr>
<tr>
<td>
<input type="text" class="change-calculator calc-from" value=""><br />
<input type="text" class="change-calculator calc-to" value="1000">
</td>
<td>
<h2 class="calc-result"></h2>
</td>
<td>
<input type="text" class="change-calculator calc-from" value=""><br />
<input type="text" class="change-calculator calc-to" value="2000">
</td>
<td>
<h2 class="calc-result"></h2>
</td>
</tr>
</table>
2
Answers
Note that I’m using
const
instead oflet
, as these are values that won’t be changed.Also, I’m not sure why you had
"input"
as a second argument in youron()
function. I assumed that it was intended to be another event, so I moved it.Consider the following.
Minor change to HTML so that
<h2>
is no longer targeted.Added function to make calculations easier.