Question

Hey I have a handful of jquery sliders called "lp-slider" set up like so:

                 <div class="xs-col-12">
                        <div class="col-xs-2 label label-default">Grit</div>
                        <div class="col-xs-9">
                            <div class="lp-slider" data-lpScore="30"></div>
                        </div>
                        <div class="col-xs-1"><img class="slider-img" src="images/close-white.png"></div>
                        <br class="clear-fix">
                    </div>
                    <div class="xs-col-12 spacer-med">
                        <div class="col-xs-2 label label-default">Self-efficacy</div>
                        <div class="col-xs-9">
                            <div class="lp-slider" data-lpScore="30"></div>
                        </div>
                        <div class="col-xs-1"><img class="slider-img" src="images/close-white.png"></div>
                        <br class="clear-fix">
                    </div>
                    <div class="xs-col-12 spacer-med">
                        <div class="col-xs-2 label label-default">Sociability</div>
                        <div class="col-xs-9">
                            <div class="lp-slider" data-lpScore="30"></div>
                        </div>
                        <div class="col-xs-1"><img class="slider-img" src="images/close-white.png"></div>
                        <br class="clear-fix">
                    </div>

I'd like to run an each statement on them so that it grabs the data attribute and uses it to set the slider value. I tried this and I can't quite seem to figure out how to get it to work. It sets up the slider but value part doesn't work correctly:

$(".lp-slider").each(function() {
    var value = $(this).data("lpScore");
    $(this).slider({
        value:value,
        range:"min",
        min:1,
        max:100,
        step:1
    });
});
Was it helpful?

Solution

To get a data attribute using jQuery's data() you have to write it in lowercase like lpscore.

Here a deep explanation of the rules applied by data Using data attributes with jQuery

Code:

$(".lp-slider").each(function () {
    var value = $(this).data("lpscore");
    $(this).slider({
        value: value,
        range: "min",
        min: 1,
        max: 100,
        step: 1
    });
});

Demo: http://jsfiddle.net/IrvinDominin/G3vy6/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top