Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI multiple sliders with amount

I have setting up some sliders on 1 page but when you slide 1 slider the amount of all the sliders change...

How can i make a slider seperate from each other? And if it is not to mutch work how can i use a span instead of a inputfield for showing the amount?

JS:

$(".slider").each(function () {
    $(".slider-range").slider({
        range: true,
        min: 0,
        max: 100,
        values: [30, 60],
        slide: function (event, ui) {
            $(".amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });
    $(".amount").val("$" + $(".slider-range").slider("values", 0) + 
                     " - $" + $(".slider-range").slider("values", 1));
});      

HTML:

 <div class="slider">
      <b>Price range:</b>
      <input type="text" class="amount" />
      <div class="slider-range"></div> 
 </div>
like image 782
Maanstraat Avatar asked Jul 15 '26 19:07

Maanstraat


1 Answers

Haven't tested it but I'm pretty sure it's an issue of not using any kind of scoping when finding ".slider-range" and ".amount" elements. The way you doing it, you're basically attaching handler for "slide" event for every ".amount" element X times (where X is a number of ".slider" elements on page).

My fix:

$(".slider").each(function () {
    // $this is a reference to .slider in current iteration of each
    var $this = $(this);
    // find any .slider-range element WITHIN scope of $this
    $(".slider-range", $this).slider({
        range: true,
        min: 0,
        max: 100,
        values: [30, 60],
        slide: function (event, ui) {
            // find any element with class .amount WITHIN scope of $this
            $(".amount", $this).val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });
    $(".amount").val("$" + $(".slider-range").slider("values", 0) + " - $" + $(".slider-range").slider("values", 1));
});    

EDIT: I forgot to put var before declaring $this variable. I've tested it and now it looks alright :)

like image 151
WTK Avatar answered Jul 17 '26 14:07

WTK