javascript - 如何根据按钮单击添加两个每行总和?

标签 javascript html jquery button sum

因此,我尝试根据按钮是否被点击,将每行总和加 2。

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>

j查询:

//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);
      })
    }
  })
});

我的问题是单击按钮会向每一行添加两个,而不是它所在的行。 任何帮助将不胜感激。

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

最佳答案

你可以试试这个:

$('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>

关于javascript - 如何根据按钮单击添加两个每行总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64067832/

相关文章:

javascript - 对每条条件语句进行分组

javascript - 行为主题 : next is not a function

javascript - 将目标的子级发送到 JQuery 中的函数

html - 呈现的字体与字体系列不同

html - 下拉选择背景图片和w/o Javascript

javascript - jQuery 生成的 html 上的事件

javascript - 与 'getElementsByClassName' + 基准相比,jQuery 中的类选择器出奇地慢

javascript - 克隆节点中的 innerText 不同

javascript - 为什么 JavaScript 的 string.split() 在某些情况下不能正常工作?

javascript - 传单不将本地镜像显示为叠加层