Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

noUiSlider: Create multiple

I'm using noUiSlider (http://refreshless.com/nouislider/) on a form which will have dozens of sliders on it. Rather than copy/pasting the code for each, I thought I could just set up an array of class names and a loop. That works; ie, it sets up working sliders. However the form also has to show the value of a slider upon update, and that's the part that I can't work out. I know how to do it with a static value but not in the loop ...

Simplified example:

JavaScript:

var steps = [
    'Never',
    'Occasionally',
    'Frequently',
    'Constant'
];
// This array will have many more
var slider_names = [
    'slider',
    'slider2'
];
var sliders = [];

for (var i = 0; i < slider_names.length; i++) {
    sliders.push(document.getElementById(slider_names[i]));
    noUiSlider.create(sliders[i], {
        start: 0,
        connect: 'lower',
        step: 1,
        range: {
            'min': [ 0 ],
            'max': [ 3 ]
        },
        pips: {
            mode: 'steps',
            density: 100
        }
    });
    sliders[i].noUiSlider.on('update', function(values, handle) {
// ***** Problem line *****
        document.getElementById(slider_names[i]+'-value').innerHTML = steps[parseInt(values[handle])];
// ***** Problem line *****
    });
}

HTML:

<div id="slider-value"></div>
<div id="slider"></div>
<div id="slider2-value"></div>
<div id="slider2"></div>  (etc...)

The problem line is highlighted above ... when using a static value (ex, 'slider2-value') it works fine, but I can't seem to figure out how to target the appropriate id when the update event triggers ... slider_names[i] obviously won't work there. I'm probably missing something obvious? Thanks!

like image 969
emmzee Avatar asked Jul 16 '15 20:07

emmzee


1 Answers

I've also stumbled into the same issue today, I've used the following code.

Basically i'm just sending all the values of the sliders to this function which then pushes all the results into an array, then i can handle the array of data however i want to.

Hopefully this can be of some use to you also.

var sliders = document.getElementsByClassName('sliders');

for ( var i = 0; i < sliders.length; i++ ) {

    noUiSlider.create(sliders[i], {
        start: 50,
        step: 5,
        connect: "lower",
        orientation: "horizontal",
        range: {
            'min': 0,
            'max': 100
        },
    });

    sliders[i].noUiSlider.on('slide', addValues);
}

function addValues(){
    var allValues = [];

    for (var i = 0; i < sliders.length; i++) {
        console.log(allValues.push(sliders[i].noUiSlider.get()));
    };

    console.log(allValues);
}
like image 140
Owen Pattison Avatar answered Nov 11 '22 09:11

Owen Pattison