0

I am working on a template that could have one or more JQuery UI Sliders.

Can I initialize all sliders from a single script if the settings for each are held within a data-options or data-id attribute on the input?

HTML would be something like:

<label for="amount">Amount <input type="text" id="amount" data-id="5000" class="ui-slider-input" readonly />
  <div class="max-slider"></div>
</label>

I have it doing a single element like this:

var sliderInput = $('#amount');
var sliderDiv = sliderInput.next('.max-slider');
var sliderMax = sliderInput.attr('data-id');
sliderDiv.slider({
  range: "min",
  value: sliderMax,
  min: 0,
  max: sliderMax,
  step: 10,
  slide: function( event, ui ) {
    sliderInput.val( ui.value );
  }
});
sliderInput.val( sliderMax ) );

But I would like to initialize multiple sliders, each with a different max and step value.

2
  • Could you show a snippet of HTML that includes more than one slider element, then you will - hopefully - get a solution that's specifically relevant to your situation, and it saves us from creating a second slider... :) Commented Oct 22, 2016 at 11:10
  • @DavidThomas The second or third slider would be identical aside from the id and data-id Commented Oct 22, 2016 at 11:37

1 Answer 1

2

You can just iterate with each()

var options = {
    range : "min",
    min   : 0,
    step  : 10,
    slide : function( event, ui ) {
        $(this).prev().val( ui.value );
    }
}

$('.sliders').each(function() {
    $(this).slider(
        $.extend({}, options, {
            value : $(this).data('id'),
            max   : $(this).data('id'),
        })
    );
});
Sign up to request clarification or add additional context in comments.

7 Comments

Can you show this working in a fiddle? When I try the value no longer changes when sliding.
Thanks, this works so far. I have updated the Fiddle to be closer to my needs. Can you tell me what I am doing wrong with the max and step values?
You have arrays in the attribute, but you probably wanted objects -> jsfiddle.net/adeneo/zxtur473/3
Great thanks, I knew I was missing something obvious!
Sorry I thought it was working, but it is actually giving TypeError: alignValue.toFixed is not a function while sliding and the sliding is not consistant...?
|

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.