1

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!

Jordan Arsenault
  • 7,100
  • 8
  • 53
  • 96

1 Answers1

2

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
        ...
    });
});
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thank you - the .each() wrap worked a treat. Although your first code block won't work because of the value of _this_, it appears to be very similar to mine except you've wrapped it in an additional set of parenthesis. What JS rules are you following here to make yours valid? Can you explain, or point me to a document that covers this kind of syntax? Thanks again. – Jordan Arsenault Jul 05 '11 at 02:21
  • @Jordan: The difference is just that I'm *immediately executing* the function you created with the `()` at the end. If you had a function `foo` and called it there (`foo()`), it would be the same thing, except you're declaring `foo` inline. Here's a good question/answer on this: http://stackoverflow.com/q/186024/497356 – Andrew Whitaker Jul 05 '11 at 02:27