我有多个输入行,所有行的末尾都有一个总计列。现在,我想将每行的总计结果放入总计列中。我试过了,但它返回的是NaN值而不是总结果。附件是我的视图和脚本,请帮助我丢失的内容???谢谢



$('body').on('change', '.bgpending, .registered', function() {
  var el = $(this);
  var totalRow = 0;
  el.closest('.dosiaPlace').find('input').each(function() {
    totalRow = totalRow + parseInt($(this).val());
  });
  el.closest('.dosiaPlace').find('.total-row').val(totalRow);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dosiaPlace">
  <div class="col-md-2">
    <label>@lang('dashboard.pastyear'):</label>
    <input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
  </div>
  <div class="col-md-2">
    <label>@lang('dashboard.warida'):</label>
    <input type="number" value="0" class="form-control registered" name="registered[]" />
  </div>
  <div class="col-md-2">
    <label>@lang('dashboard.total'):</label>
    <input type="text" class="form-control total-row" />
  </div>
</div>





结果:

javascript - jQuery在连续计算多个输入时返回NaN值-LMLPHP

最佳答案

我认为容器.dosiaPlace具有3个输入:.bgpending.registered.total-row。您的el.closest('.dosiaPlace').find('input')会找到所有这3个,包括.total-row。但是.total-row是空的(最初),所以

totalRow = totalRow + parseInt($(this).val());


因为它导致

totalRow = totalRow + parseInt('');


而且空字符串不能parseInt(导致NaN)。 (您可能也不想包含.total-row

使用input:not(.total-row')代替input



$('body').on('change', '.bgpending, .registered', function() {
  var el = $(this);
  var totalRow = 0;
  el.closest('body').find('input:not(.total-row)').each(function() {
    totalRow = totalRow + parseInt($(this).val());
  });
  el.closest('body').find('.total-row').val(totalRow);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
  <label>@lang('dashboard.pastyear'):</label>
  <input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
  <label>@lang('dashboard.warida'):</label>
  <input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
  <label>@lang('dashboard.total'):</label>
  <input type="text" class="form-control total-row" />
</div>

关于javascript - jQuery在连续计算多个输入时返回NaN值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59589100/

10-12 13:11
查看更多