views:

15

answers:

1

I'm using jQuery slider for making range sliders. By moving the sliders the corresponding input text field is updated.

The jquery code is:

jQuery("form#filterform fieldset.text").each(function(index){

        var this_slider = jQuery(this).find("#slider"); 
        $this_slider = jQuery(this_slider);
        var this_text = jQuery(this).find("input");
        $this_text = jQuery(this_text);

        var this_output = new jQuery(this).find("span#current");
        $this_output = jQuery(this_output);

        $this_slider.empty().slider({
            range: true,
            min: 0,
            max: 100,
            values: [0, 100],
            slide: function(event, ui) {
            $this_text.val(ui.values[0] + ' - ' + ui.values[1]);
            }
        });
        $this_text.val($this_slider.slider("values", 0) + ' - ' + $this_slider.slider("values", 1));
});

The problem is, all sliders update the value of the last generated slider. Anybody can spot the problem in the above code?

+3  A: 

For some reason you duplicate all your variables with a $ version of them (although they all are jquery objects).

You use those versions in the callback function, and since they are not declared with the use of var they are global. so they all point to the same thing.. (namely the last defined)

you should change the

    var this_slider = jQuery(this).find("#slider"); 
    $this_slider = jQuery(this_slider);
    var this_text = jQuery(this).find("input");
    $this_text = jQuery(this_text);

    var this_output = new jQuery(this).find("span#current");
    $this_output = jQuery(this_output);

to

    var $this_slider = jQuery(this).find("#slider"); 
    var $this_text = jQuery(this).find("input");
    var $this_output = jQuery(this).find("span#current");

and it would work ..

Gaby
Thanks a lot! I'm totally new in jQuery (and js in general)
Zack
@Zack, the use of `$` in front of variable names is just for personal convenience. It is not a requirement, nor does it have any effect in the functionality of your code..
Gaby
Thanks for that. Found the code somewhere, and I must confess those $ confused me a bit.
Zack