Jordan Arsenault
Jordan Arsenault

Reputation: 7388

jQuery UI slider initialization

I have multiple sliders on a page each with class "slider" and each is prefixed with a checkbox. When the page is loaded, the checkboxes are populated via PHP as either checked or unchecked. Based on this, I would like to enable or disable the sliders.

Removing the irrelevant parts, I have:

$(".slider").slider({
        ...
        disabled: function()
        {
            var $field = $(this).prevAll("input");
            return $field.is(':checked');
        },
        ...
});

I am not even sure if it is possible to pass an anonymous function to the disabled option. Is this legit? It doesn't seem to be working...

Of course I could initialize #slider1, #slider2, #slider3...etc seperately, but I'm looking for the most elegant and compact solution.

Is it that $(this) has gone out of scope now that it's inside of the option? How does javascript work in these cases? Provided it hasn't... I know the $(this).prevAll("input") selector is accurate as I've checked it with Firebug.

Thoughts? Thanks!

Upvotes: 1

Views: 3046

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

am not even sure if it is possible to pass an anonymous function to the disabled option. Is this legit?

Nope. You can't pass a function reference as an argument to that option.

You could immediately execute that anonymous function, but the value of this would be wrong:

$(".slider").slider({
        ...
        disabled: (function()
        {
            var $field = $(this).prevAll("input");
            return $field.is(':checked');
        })(),
        ...
});

As a workaround, you could wrap your code in an .each() block:

$(".slider").each(function () {
    var $this = $(this);
    var disabled = $this.prevAll("input").is(":checked");
    $(this).slider({
        ...
        disabled: disabled
        ...
    });
});

Upvotes: 2

Related Questions