Loop + Add to Array on Blur

为君一笑 提交于 2021-01-28 22:00:39

问题


I am having a little bit of difficulty understanding how to do this. However here it goes.

There are a bunch of input fields that user can add to.

I need to write a jQuery script without adding anything to the markup of the HTML explicitly.

  1. Find all elements with a class of inputAmt
  2. If user blurs form input field the jQuery script would trigger.
  3. Add all the value to find the total.
  4. If user subtracts anything it needs to reflect the total.

Little complicated for me I would appreciate all the help I can get.


回答1:


First lets get all elements with inputAmt class.

var elements = $('.inputAmt');

now lets create a function that adds their values

function addElementValues(){
   var sum = 0;
   elements.each(function(){
      sum += parseFloat(this.value);
      // when this.value is empty or non numeric the parseFloat returns NaN (Not A Number)
      // so you might want to do sum += parseFloat(this.value) || 0;
      // to ignore the NaN values
   });
   // do something with the sum value here
   // like display it on some element
}

finally lets use this function when any field is blurred

elements.on('blur', addElementValues);

Full working example

var elements = $('.inputAmt');

function addElementValues() {
  var sum = 0;
  elements.each(function() {
    sum += parseFloat(this.value) || 0;
  });
  // do something with the sum value here
  // like display it on some element
  $('#total').text( sum );
}

elements.on('blur', addElementValues);
.w70 {
  width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="txtr">
        <input type="text" class="inputAmt w70" name="something">
      </td>
      <td class="txtr">
        <input type="text" class="inputAmt w70" name="something1">
      </td>
      <td class="txtr">
        <input type="text" class="inputAmt w70" name="something2">
      </td>
      <td class="txtr">
        <input type="text" class="inputAmt w70" name="something3">
      </td>
      <td class="txtr">
        <input type="text" class="inputAmt w70" name="something4">
      </td>
    </tr>
  </tbody>
</table>
<div id="total"></div>


来源:https://stackoverflow.com/questions/29148865/loop-add-to-array-on-blur

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!