9

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

2 Answers 2

9
+50

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);
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

4

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);
        }
    });
});

1 Comment

This solution is better when using multiple sliders

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.