Home > Software design >  I need to show calculation result in previous table cell
I need to show calculation result in previous table cell

Time:09-19

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"  style="width:100%">
  <thead>
    <tr>
      <th>Result</th>
      <th>Calculator</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="text" >
      </td>
      <td>
        <input type="text"  value="1500"><br>
        <input type="text"  value="">
      </td>
    </tr>
  </tbody>
</table>

CodePudding user response:

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"  style="width:100%">
  <thead>
    <tr>
      <th>Result</th>
      <th>Calculator</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="text"  readonly />
      </td>
      <td>
        <input type="text"  value="1500" /><br />
        <input type="text"  value="" />
      </td>
    </tr>
  </tbody>
</table>

  • Related