user1054080
user1054080

Reputation:

Calculate total values from select elements by looping through

I want to loop through some elements extract there value and calculate the total value of all integers. See my code below:

jquery('select').each(function(){
            var total = jquery(this).attr('val');

            if (total){

                total += parseInt(total);
                console.log(total);
            }
        });

The code just returns the selected value twice, no calculation done.

Upvotes: 0

Views: 196

Answers (2)

vinayakj
vinayakj

Reputation: 5681

var total=0;
jquery('select').each(function(){
           total += Number(jquery(this).val());
});

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038990

You probably should move the total variable outside your loop:

var total = 0;

jQuery('select').each(function() {
    var value = jQuery(this).attr('val');

    if (value) {
        total += parseInt(value);
    }
 });

 console.log(total);

Also it's worth mentioning that val is not a pretty standard HTML attribute. Maybe you wanted to actually use the selected value in which case you could use:

 var value = jQuery(this).val();

Also notice that jquery should probably be jQuery, don't forget that javascript is a case sensitive language.

Upvotes: 1

Related Questions