1

I have a series of input boxes into which users will input numerical values to be stored in an array. I would like for these values to be added and their sum shown via an alert. However I cannot determine how to pass these values to the array via the click of a button like I hope to. Here is my code:

$('#check').click(function() {
    var arr = [];
  getSum = function() {
    for ( i = 0; i < 100; i++){
    arr[i] =
    $('input:number').map(function(){
        return this.value;
    });
    }
    var sum = 0;
    var n = arr.length;
for(var i = 0; i < n ; i++) {
sum += parseInt(arr[i]);

}
alert(sum);
}
 getSum();
});

with HTML markup:

<input type="number" id="field1" />
<input type="number" id="field2" />
<input type="number" id="field3" />
<button type="button" id="check">Calc</button>

Also, I have figured out how to dynamically add inputs so that the user may include more values in the sum, but I am not sure how this would affect the code. Would this still be sufficient?

1
  • incorrect selector :number doesn't exist AFAIK and map() returns an array. You are over complicating things Commented Jan 6, 2016 at 3:38

2 Answers 2

4

I've shortened your code. input[type=number] is a proper selector for what you're trying to do and it will find all new dynamically created inputs with type number.

$('#check').click(function() {
    var sum = 0;
    $('input[type=number]').each(function(i, input) {
        sum += Number(input.value);
    });
    alert(sum);
});
Sign up to request clarification or add additional context in comments.

4 Comments

I set up this fiddle jsfiddle.net/P7QXa/27 , but it doesn't seem to work.
@newbie2015 That fiddle works for me. What is it that does not seem to work?
It didn't alert me of the sum. I was using Mozilla Firefox if that makes a difference. I just tried it on Safari and it worked no sweat.
+1 for a solution that worked. I went for the @HarishKommuri solution below though, with my addition. Still, many thanks!
1
 var arr = [], sum = 0;

 $("#check").click(function() {
   $("input[type=number]").each(function() {
      arr.push($(this).val());
      sum += $(this).val();
   });
});

1 Comment

I added this to the sum += line: parseInt($(this).val()); so that it adds the values rather than just outputting them to an array. Thanks for a solution that, otherwise, works quite well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.