Search code examples
javascripthtmljquerybuttonsum

How can I add two each row sum depending on a button click?


So, I'm trying to add two to each row sum depending on whether or not the button is clicked.

HTML:

<table>
<tr>
<td>
<input type="checkbox" class="prof" name="prof" value="0">
<input class="mod" name="mod" type="text" value='2'>
<input class="savings" name="savings" type="text">
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="prof" name="prof" value="0">
<input class="mod" name="mod" type="text" value='4'>
<input class="savings" name="savings" type="text">
</td>
</tr>
</table>

jquery:

//when document is ready, have numbers appear in each '.savings'
$(document).ready(function() {
//on button click, change the number depending on if checked or not
  $('input[type="checkbox"]').click(function() {
    if ($('input[type="checkbox"]').prop("checked") == true) {
      $('tr').each(function() {
        var sum = 2
        $(this).find('.mod').each(function() {
          var mod = $(this).val();
          if (!isNaN(mod) && mod.length !== 0) {
            sum += parseFloat(mod);
          }
        });
        $('.savings', this).val(sum);
      })
    } else {
      $('tr').each(function() {
        var sum = 0
        $(this).find('.mod').each(function() {
          var mod = $(this).val();
          if (!isNaN(mod) && mod.length !== 0) {
            sum += parseFloat(mod);
          }
        });
        $('.savings', this).val(sum);
      })
    }
  })
});

My problem is that the button click adds two to every row and not the row it's sitting in. Any help would be appreciated.

JSfiddle: https://jsfiddle.net/sheepishlamb/3p9gary8/


Solution

  • You can try this :

    $('input[type="checkbox"]').click(function() {
      var mod = $(this).next('.mod').val();
      var sum = ($(this).is(":checked")) ? 2 : 0;
      if (!isNaN(mod) && mod.length !== 0) {
        sum += parseFloat(mod);
      }
      $(this).siblings('.savings').val(sum);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tr>
        <td>
          <input type="checkbox" class="prof" name="prof" value="0">
          <input class="mod" name="mod" type="text" value='2'>
          <input class="savings" name="savings" type="text">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" class="prof" name="prof" value="0">
          <input class="mod" name="mod" type="text" value='4'>
          <input class="savings" name="savings" type="text">
        </td>
      </tr>
    </table>