I need to show calculation result in previous table cell

Viewed 18

I have a jQuery percentage calculator which is working using .closest('td'). I need to show the result in the previous table cell <td>.

$(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));
  $td.next().find('.calc-result').val(result.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="abcde-table" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Result</th>
      <th>Calculator</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="text" class="calc-result">
      </td>
      <td>
        <input type="text" class="change-calculator calc-from" value="1500"><br>
        <input type="text" class="change-calculator calc-to" value="">
      </td>
    </tr>
  </tbody>
</table>

1 Answers

There's three issues in your code. Firstly the event delegated signature of on() needs three arguments, not four. Remove the first one, as the input event is all you need.

Secondly, the .calc-result input is in the td previous to the current one so use prev(), not next().

Lastly, the input only has a value, so remove the line setting its text().

$(document).on("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.prev().find('.calc-result').val(result.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table id="abcde-table" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Result</th>
      <th>Calculator</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="text" class="calc-result" readonly />
      </td>
      <td>
        <input type="text" class="change-calculator calc-from" value="1500" /><br />
        <input type="text" class="change-calculator calc-to" value="" />
      </td>
    </tr>
  </tbody>
</table>

Related