Search code examples
jquery-uiaverageuislider

Adding text input that shows average of several jQuery UI sliders


I have several jQueryUI sliders working with this code:

jQuery(document).ready(function ($)
{
    $( '.rwmb-slider' ).each( function() {

        var $this = $( this ),
            $input = $this.siblings( 'input' ),
            $valueLabel = $this.siblings( '.rwmb-slider-value-label' ).find( 'span' ),
            value = $input.val(),
            options = $this.data( 'options' );

        if ( !value )
        {
            value = 0;
            $input.val( 0 );
            $valueLabel.text( '0' );
        }
        else
        {
            $valueLabel.text( value );
        }

        // Assign field value and callback function when slide
        options.value = value;
        options.slide = function( event, ui )
        {
            $input.val( ui.value );
            $valueLabel.text( ui.value );

        };

        $this.slider( options );    

    });

});

JSFIDDLE: http://jsfiddle.net/q2BwE/

Everything works good but I'm struggling integrating in this code a function that allows me to display in a text input an average of the sliders which value is different than '0'.

Can you help me guys? Thank you


Solution

  • Here's one way to do it: jsFiddle example.

    I added a text field (<input name="average" type="text" readonly />) to display the average that gets calculated after any of the sliders finish moving. Then I added the following code to do the calculation:

    options.change = function (event, ui) {
        var avg = 0;
        var div = 0;
        $('.rwmb-slider').each(function () {
            avg += ($(this).slider('value'));
            if($(this).slider('value')>0)div++
        })
        $('input[name=average]').val(avg/div);
    };