jquery在加载页面时进行计算(在函数中)

时间:2016-02-05 18:42:10

标签: jquery

我需要计算输入的平均值,求和并将其打印在输入#average中。

我正在使用http://viralpatel.net/blogs/sum-html-textbox-values-using-jquery-javascript/

中的这个(改编的)代码
<script>
    $(document).ready(function(){
       //iterate through each textboxes and add keyup
       //handler to trigger sum event
       $(".sum").each(function() {
         $(this).keyup(function(){
           calculateSum();
         });
       });
    });

    function calculateSum() {
       var sum = 0;
       //iterate through each textboxes and add the values
       $(".sum").each(function() {
         //add only if the value is number
         if(!isNaN(this.value) && this.value.length!=0) {
           sum += parseFloat(this.value) /7;
         }
       });
       //.toFixed() method will roundoff the final sum to 2 decimal places
       $("#average").val(sum.toFixed(2));     
    }
</script>

EDITED

我现在有一个问题:

1)当我加载我的页面(并且inputs.sum从db检索数据)时,#average为空,直到我不修改输入。

我应该如何修改我的代码?

1 个答案:

答案 0 :(得分:1)

我的建议是计算文档就绪的平均值以及每次对任何输入字段进行更改时(Iused输入字段类型编号,但此代码段也适用于输入类型文本):

function calculateAverage() {
  var sum = 0;
  var numOfInputs = $(".sum").length;
  $(".sum").each(function (index, ele) {
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }
  });
  $("#average").val((sum / numOfInputs).toFixed(0));
}

$(function () {
  // compute the average at document ready
  calculateAverage();
  
  // compute the average whenever an input field change
  $(".sum").on('input', function() {
    calculateAverage();
  });
});
body {
  font-family: sans-serif;
}
#average {
  font-size: 18px;
  font-weight: bold;
  color:#174C68;
  margin-left: 10px;
}
input {
  background-color: #FEFFB0;
  font-weight: bold;
  text-align: right;
  width: 10%;
}
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<form>
    Number 1:
    <input type='number' class="sum" value="1"><br>
    Number 2:
    <input type='number' class="sum" value="2"><br>
    Number 3:
    <input type='number' class="sum" value="3"><br>
    Average:
    <input type="number" id="average">
</form>

如果你有更多的平均值来计算for循环应该是:

function calculateAverage() {
  var sum = 0;
  var numOfInputs = 0;
  for(var i = 1; i<5; i++) {
    sum = 0;
    numOfInputs =  $(".sum" + i).length;
    $(".sum" + i).each(function (index, ele) {
      if (!isNaN(this.value) && this.value.length != 0) {
        sum += parseFloat(this.value);
      }
    });
    $("#average" + i).val((sum / numOfInputs).toFixed(0));
  }
}
$(function () {
  calculateAverage();
  $('[class^="sum"]').on('input', function() {
    calculateAverage();
  });
});
body {
  font-family: sans-serif;
}
label {
  display: inline-block;
  font-size: 18px;
  text-align: left;
  width: 15%;
}
input.average {
  background-color: #FEFFB0;
  font-size: 18px;
  font-weight: bold;
  text-align: right;
  color:#174C68;
  width: 10%;
}
input[class^="sum"] {
  background-color: #FEFFB0;
  font-weight: bold;
  text-align: right;
  width: 10%;
}
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<form>
    <label>Number 1:</label>
    <input type='number' class="sum1" value="1">
    <input type='number' class="sum2" value="1">
    <input type='number' class="sum3" value="1">
    <input type='number' class="sum4" value="1"><br>
    <label>Number 2:</label>
    <input type='number' class="sum1" value="2">
    <input type='number' class="sum2" value="2">
    <input type='number' class="sum3" value="2">
    <input type='number' class="sum4" value="2"><br>
    <label>Number 3:</label>
    <input type='number' class="sum1" value="3">
    <input type='number' class="sum2" value="3">
    <input type='number' class="sum3" value="3">
    <input type='number' class="sum4" value="3"><br>
    <label>Average:</label>
    <input type="number" class="average" id="average1">
    <input type="number" class="average" id="average2">
    <input type="number" class="average" id="average3">
    <input type="number" class="average" id="average4">
</form>

相反,如果您可以在表格中组织输入,结果将更加简单:

function calculateAverage() {
  var sum = 0;
  var numOfInputs = $('table > tbody > tr').length;
  // clear the averages
  $('table > tfoot > tr > td:gt(0)').each(function(index, ele) {
    $(ele).find('.average').val('0');
  });
  // for each row in the body
  $('table > tbody > tr').each(function(index, ele) {
    // for each column in the current row
    $(ele).find('td:gt(0)').each(function(index, ele) {
      // update the corresponding average computing the sum
      var currVal = parseFloat($(ele).find('.sum').val()) || 0;
      var currAverageObj = $('table > tfoot > tr > td:eq(' + (index + 1) + ') > input');
      currAverageObj.val(parseFloat(currAverageObj.val()) + currVal);
    });
  });
  // adjust the average value dividing by the number of elements
  $('table > tfoot > tr > td:gt(0)').each(function(index, ele) {
    var currentAverageObj = $(ele).find('.average');
    currentAverageObj.val((parseFloat(currentAverageObj.val()) / numOfInputs).toFixed(0));
  });
}
$(function () {
  calculateAverage();
  $('[class^="sum"]').on('input', function() {
    calculateAverage();
  });
});
body {
  font-family: sans-serif;
}
.average {
  font-size: 18px;
  font-weight: bold;
  color:#174C68;
  text-align: right;
  width: 99%;
}
input {
  background-color: #FEFFB0;
  font-weight: bold;
  text-align: right;
}
td {
  width: 50px;
}
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<form>
    <table>
        <thead>
            <tr>
                <th></th>
                <th>Value1</th>
                <th>Value2</th>
                <th>Value3</th>
                <th>Value4</th>
                <th>Value5</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Elems1</td>
                <td><input type='text' class="sum" value="1"></td>
                <td><input type='text' class="sum" value="2"></td>
                <td><input type='text' class="sum" value="3"></td>
                <td><input type='text' class="sum" value="4"></td>
                <td><input type='text' class="sum" value="5"></td>
            </tr>
            <tr>
                <td>Elems2</td>
                <td><input type='text' class="sum" value="1"></td>
                <td><input type='text' class="sum" value="2"></td>
                <td><input type='text' class="sum" value="3"></td>
                <td><input type='text' class="sum" value="4"></td>
                <td><input type='text' class="sum" value="5"></td>
            </tr>
            <tr>
                <td>Elems3</td>
                <td><input type='text' class="sum" value="1"></td>
                <td><input type='text' class="sum" value="2"></td>
                <td><input type='text' class="sum" value="3"></td>
                <td><input type='text' class="sum" value="4"></td>
                <td><input type='text' class="sum" value="5"></td>
            </tr>
            <tr>
                <td>Elems4</td>
                <td><input type='text' class="sum" value="1"></td>
                <td><input type='text' class="sum" value="2"></td>
                <td><input type='text' class="sum" value="3"></td>
                <td><input type='text' class="sum" value="4"></td>
                <td><input type='text' class="sum" value="5"></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td>Average</td>
                <td><input type="text" class="average"></td>
                <td><input type="text" class="average"></td>
                <td><input type="text" class="average"></td>
                <td><input type="text" class="average"></td>
                <td><input type="text" class="average"></td>
            </tr>
        </tfoot>
    </table>
</form>