Search code examples
jqueryjquery-uijquery-calculation

Calculate and output average from jQuery UI sliders


I try to make it as simple as possible: I have six jQuery UI sliders, I need to take their values if they're value is different from 0, and display an average, and is driving me crazy so far.

Basically I have six of these (their names go from pm_rating_c1, pm_rating_c2, etc..):

<input type="hidden" name="pm_rating_c1" value="60">

I need to output the average in "real time" in this input field:

<input type="text" class="rwmb-text" name="pm_overall_score" id="pm_overall_score" value="" size="30">

Solution

  • Check this out I made a class so it would be easier to loop through

    http://jsfiddle.net/6SftR/

    JS CODE

    var sum = 0 ; 
     var nums = 0;
    $('.slider').bind({
    
        slidechange : function(event,ui) {
          sum = 0;
          nums  = 0;
        $('.slider').each(function(){
    
            var value = $( this ).slider( "option", "value" );
            if(value > 0 ) 
             {
                sum += value ; 
                nums++;
              }
    
            }); 
           var avg = sum / nums ; 
           $('.average').val(Math.floor(avg));
           console.log(avg); 
        }
    }).slider();
    

    HTML CODE

    <div class="slider"></div>
    <div class="slider"></div>
    <div class="slider"></div>
    <div class="slider"></div>
    <div class="slider"></div>
    <div class="slider"></div>
    
    
        <input type="text" class="average" name="pm_overall_score" id="pm_overall_score" value="" size="30">
    

    I hope this will help