-5

How could I sum the fields automaticly (by each function) to sum some input fields like this:

<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />

Thank you very much if anyone has a suggestion?

onbids
  • 53
  • 1
  • 7

2 Answers2

1

Use jQuery;

<script src="{path to jquery}/resources/js/vendor/jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function() {
 var total = 0;
 $.each($('input'), function(){
   total += parseInt($(this).val(), 10); //use radix 10 to ensure correct parseInt val
 });
 console.log(total);
});
</script> 
4m1r
  • 12,234
  • 9
  • 46
  • 58
  • Are you sure the values to be summed are integers? And why jquery, a whole library for such a trivial task. – Xotic750 Apr 18 '13 at 21:59
  • 2
    Ha! Do yourself a favor and add jQuery to your project. Its super lightweight and more than half of the web developers on the planet use it. True, you can do this without and you might want to check and skip summing values that aren't numbers. Just going for a concise and easy to read solution. Yours is cool too. – 4m1r Apr 18 '13 at 22:10
  • I have no problem with jquery, I like it and use it when appropriate, it just seems that everyone tries to use it for everything these days and the underlying art of javascript is being overlooked. Javascript is beautiful, powerful and readable too, where would jquery be without it? ;) – Xotic750 Apr 18 '13 at 22:14
  • Just as a comparison, take a look at this jsperf (http://jsperf.com/jq-sum-elements-vs-raw-js) of our suggestions, and the pure javascript is also adding an event listener to each input element. – Xotic750 Apr 18 '13 at 22:22
0

On jsfiddle

<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />

var inputs = document.getElementsByTagName("input");

function sumIt() {
    var sum = Array.prototype.reduce.call(inputs, function (a, b) {
        return a + parseFloat(b.value);
    }, 0);

    console.log(sum);
}

Array.prototype.forEach.call(inputs, function (input) {
    input.addEventListener("keyup", sumIt, false);
});
Xotic750
  • 22,914
  • 8
  • 57
  • 79