Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting jQuery ui slider params from html data attributes

Tags:

jquery-ui

I want to embed the max of my sliders range in an html data parameter. I did some debug, and despite the fact that the data can be accessed and is a number, the slider will still use the default max of 100.

My HTML:

<div class="slider" data-max="10"></div>
<label for="slider_value">Slider Value:</label>
<input type="text" id="slider_value" />

My Javascript:

$(document).ready(function () {
    $("div.slider").slider({
        min: 0,
        max: $(this).data("max"),
        slide: function (event, ui) {
            $("input#slider_value").val(ui.value);
        }
    });
});

See this fiddle

like image 488
danatron Avatar asked Feb 04 '13 07:02

danatron


2 Answers

When the argument object for slider() is evaluated, this is a reference to the document object, not div.slider. You'd need to find div.slider again or save a reference to it (demo):

$(document).ready(function () {
    var div = $("div.slider");
    div.slider({
        min: 0,
        max: div.data("max"),
        slide: function (event, ui) {
            $("input#slider_value").val(ui.value);
        }
    });
});
like image 85
Jeffery To Avatar answered Oct 20 '22 05:10

Jeffery To


Use the jQuery UI create event with option method to set options dynamically:

$(document).ready(function() {
    $('div.slider').slider({
        min: 0,
        create: function(event, ui) {
            $(this).slider('option', 'max', $(this).data('max'));
        },
        slide: function(event, ui) {
            $("input#slider_value").val(ui.value);
        }
    });
});
like image 45
Nikola K. Avatar answered Oct 20 '22 03:10

Nikola K.