2

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
2
  • You overwrite your total inside your each every single time, you need to specify your total outside the scope of the event binding. If you're looking to keep totals independently for the 2 sliders, that will require a little extra brain power. Commented Jul 30, 2013 at 0:24
  • Possible duplicate of Sum using jQuery each function Commented Oct 12, 2016 at 13:03

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

2 Comments

Fast, concise, and clean. Thank you so much!
if forget to parseInt

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.