1

I am trying to add values those are separated by comma.

Tried-

$(function(){
    $('#sum').keyup(function(){
    var prevalue=$('#sum').val().split(",");
        for (i=0;i<prevalue.length;i++){
            prevalue+=prevalue[i];
             $('h1').html(prevalue);
}

    });

});

This array goes infinite and doesn't loop values.

How can I add values seperated by comma?

Fiddle

0

7 Answers 7

5

You are modifying the variable prevalue (shared by the loop condition) inside the loop where you check for length each time as a loop condition. And each time it adds something to it inside the loop so it goes on an on. It used to be an array and after adding the string to it, it coerses to string from array and then on wards it checks for the length of the string and you keep on appending to it, it goes on and on.

Try:

$(function(){
    $('#sum').keyup(function(){
    var prevalue=$('#sum').val().split(","), sum = 0;
        for (var i=0;i<prevalue.length;i++){
            sum += parseInt(prevalue[i], 10) || 0; //<--- Use a parseInt to cast it or use parseFloat

         }
     $('h1').html(sum); //<-- move it to out of the loop
    });
 });

Fiddle

Your code:

$(function () {
    $('#sum').keyup(function () {
        var prevalue = $('#sum').val().split(","); //<-- Iteration 1 prevalue is an array
        for (i = 0; i < prevalue.length; i++) { //iteration1 : it looks for array.length
            prevalue += prevalue[i]; //Changes the variable shared by the loop to string from array and string also has its length. And next time onwards it adds to itself a char from the string and length increases and loop goes infinitely.
            $('h1').html(prevalue); //<-- Doesn't make any sense here.
        }
    });
});
Sign up to request clarification or add additional context in comments.

8 Comments

you mean length of string goes infinite after first iteration? How can it be possible?
@Manoz 200%... :) Did you not understand with my explanation? You are modifying the variable used in the loop condition. and you append a char to it right after first iteration, so then it checks for new length, and it goes infinitely. Just place a console.log( and break it after 10 iteration manually)
so it is parsing problem due to string typecast to integer. Right?
@Manoz Not just parsing problem, you shouldn't modify the variable used in loop condition as well which is a risky stuff.
you might want to consider replacing sum += parseInt(prevalue[i], 10); with sum += parseInt(prevalue[i], 10) || 0;. That way when the value of #sum ends in a comma (as it occasionally will as people type) you'll still get a number value for sum. Just a thought.
|
2

You have two problems:

1.You iterrate over the value you change, and every interation you make the value longer, and therefore its length is increasing and making your loop infinite

2.When you use += operator with string on the sum variable it is translated as string concatenation. in order to translate it as int increment, use parseInt().

$(function(){
    $('#sum').keyup(function(){
    var prevalue=$('#sum').val().split(",");
        sum = 0;
        for (i=0;i<prevalue.length;i++){
            sum+=parseInt(prevalue[i]);
}
        $('h1').html(sum);
    });
});

Comments

2

Try this instead:

$(function () {
    $('#sum').keyup(function () {
        var finalvalue = 0;
        var prevalue = $('#sum').val().split(",");
        for (i = 0; i < prevalue.length; i++) {
            finalvalue += parseInt(prevalue[i]);
        }
        $('h1').html(finalvalue);
    })
});

Demo here

This -> prevalue+=prevalue[i]; frezes your browser.

  • I added a new variable finalvalue to get the sum or the values of prevalue inside the loop.
  • Your array, generated by split, has strings. So I used parseInt() to get numbers that you can add, otherwise += will work as a string concatenation.
  • I removed the $('h1').html(finalvalue); from inside the loop, no need for it to render on each loop. So I put it after the loop.

Comments

1

There is a much better to handle what you are doing, as an addition to the main problem that you had, which was modifying the same array which was supposed to contain the array.

$(document).ready(function() {
    $('#sum').keyup(function() {
        var sum = 0;
        $('#sum').val().split(',').map(function(n) {
            if(!n) return;
            sum += parseInt(n);
            return sum;
        });
        $('#result').text(sum);
    });
});

See the demo here.

7 Comments

Why do you think using a map better? Also the way you have it implemented doesn't even utilize the return of map. Also it is Ecma5 you need a shim for older browsers? and also this could be slower considered to just using a for loop for this purpose.
Map is marginally better than using the for loop. You can see the results here. jsperf.com/achrome-for-vs-map I agree with the shim for older browsers, and the return is done this way to avoid NaN from being displayed just after a comma is entered.
Na, you need to cache the length in for-loop and check this jsperf.com/achrome-for-vs-map/2 , it is intermittent. Plus for this purpose if you thinnk of using a map then forEach would be better as you are not utilizing the map's return(which is generally used for transforming array of objects to a array of objects with changes)
Plus sorry your benchmark doesn't even go inside the keyup., you need to put it outside and set up and array,
Sorry, it was still running the old rev. Thanks for the explanation. :)
|
1

You are overwriting prevalue while you're still operating on it. Use another variable instead.

$(function(){
    $('#sum').keyup(function(){
    var prevalue=$('#sum').val().split(","), value = 0;
        for (i=0;i<prevalue.length;i++){
            value+=parseInt(prevalue[i], 10);
             $('h1').html(value);
        }  

    });

});

Comments

0

This doesn't work because you use the same variable for the values and the sum. Try something like this:

$(function(){
    $('#sum').keyup(function() {
        var values = $('#sum').val().split(",");
        var sum = 0;
        for (i = 0; i < values.length; i++) {
            // At this point values[i] is still a string, so you need to parse it to float or int
            sum += parseFloat(values[i]);
        }

        $('h1').html(sum);
    });
});

Comments

-1

Just try with this one...........

$(function(){
    $('#sum').keyup(function(){
    var prevalue=$('#sum').val().split(",");
    var value = '';
        for (i=0;i<prevalue.length;i++){
            value+=prevalue[i];
             $('h1').html(value);
        }  

    });

});

Comments

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.