jahrichie
jahrichie

Reputation: 1235

jquery loop over input value and get sum

I have input sliders (see jsfiddle) that on change i'd like to loop through their values and get a total.

I wrote the code I thought would do this, but i failed, see the fiddle and thank you so much in advance!

fiddle

Percentage Sliders<br><br>
<input type="tex" class="slida" type="text" data-slider="true" data-slider-range="0,100" data-slider-step="25" data-slider-snap="true" data-slider-theme="volume" >
<br><br>

<input type="tex" class="slida" type="text" data-slider="true" data-slider-range="0,100" data-slider-step="25" data-slider-snap="true" data-slider-theme="volume" > 


$(".slida").bind("slider:changed", function (event, data) {
  console.log("Changed Value: ", data.value);
  $(this).each(function() {
    total = 0;
    $(this).each(function() {
        total += parseInt( $(this).val() );    
    });     
  });  
  console.log("TOTAL: ", total)

});
// end

Upvotes: 2

Views: 11136

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50767

The $(this) you iterate over is only the element that is changed, therefore $.each() will not serve any purpose under that context...however

var total = 0;
$('.slida').each(function(){
   total += parseInt($(this).val());
});

Would definitely fit the mold, as you access the value of all the sliders, instead of just the one that you're firing the event on.

As usual, here's your Fiddle

Upvotes: 14

Related Questions