Search code examples
jqueryjquery-uijquery-slider

Jquery slider allocate label words to values


This is a bit like the problem posted here: Yes or no toggle or slider - but i can't get the solution to work in this example.

I have a horizontal incremental range slider which i would like to modify so that the labels are decoded to small - medium - large for values 1 - 2 - 3

I've tried sticking an array to decode but i just can't get it to work right.

Here's what i have so far:

    <script>
        $(function() {
            $( "#slider-range" ).slider({
                range: true,
                min: 1,
                max: 3,
                step: 1,
                values: [ 2, 3 ],
                slide: function( event, ui ) {
                    $( "#amount" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
                }
            });
            $( "#amount" ).val( $( "#slider-range" ).slider( "values", 0 ) +
                " - " + $( "#slider-range" ).slider( "values", 1 ) );
        });
    </script>

so that if positions 2 - 3 were selected (as is the default), the label would read 'medium - large'.

Any help or direction would be much appreciated!

Thanks


Solution

  • What about this?

    It uses a mapper object instead of an array but also includes a function that returns a string instead of creating it yourself:

    $(function() {
    
        // mapper    
        var valueMap = {
            1 : "small",
            2 : "medium",
            3 : "large",
            getText : function(arr) {
                return this[arr[0]] + " - " + this[arr[1]];
            }
        };
    
        // initial range slider values
        var initial = [2, 3];
    
        // initialize slider
        $( "#slider-range" ).slider({
            range: true,
            min: 1,
            max: 3,
            step: 1,
            values: initial,
            slide: function( event, ui ) {
                $("#amount").val(valueMap.getText(ui.values));
            }
        });
    
        // initialize value display
        $("#amount").val(valueMap.getText(initial));
    
    });