April 3, 2012

How can I have the user change options of the jQuery UI Slider?

Question by Sam Pellino

I have a jQuery UI slider on my page. It starts out with:

$( "#slider" ).slider({
    value: 6,
    min: 6,
    max: 120,
    step: 6

Which works fine.

I have a select element next to it with 6, 12, and 24 as options.
What I would like to accomplish is for the user to select 12, and the slider’s step, min, and value all go to 12 (same for 24). I have already tried to build a function:

    $( "#slider" ).slider( "option", "value", $(this).val() );
    $( "#slider" ).slider( "option", "min", $(this).val() );
    $( "#slider" ).slider( "option", "step", $(this).val() );
    $( "#slider" ).slider( "option", "max", 120 );

However all this does is make is go to value 12, then upon clicking the slider, it jumps all the way to the end (120) and just stays there.

Do I need to destroy the slider and make it again from scratch?

EDIT #1:

I did just download Firebug and check the slider with the console, and the values are all returning correct (min=12,value=12,step=12,max=120). Does anyone know why it’s being so stubborn and jumping/sticking to the end?

Answer by DigitalBiscuits

Found the issue.
You need to parse the value from the <select> to an int before you use it to change the options of the slider.

    var currentVal =  parseInt($("#slider").slider("value"));
    var newOptions = parseInt($(this).val());
    $( "#slider" ).slider( "value", currentVal);
    $( "#slider" ).slider( "option", "min", newOptions );
    $( "#slider" ).slider( "option", "step", newOptions );
    $( "#slider" ).slider( "option", "max", 120 );

Working Example


Answer by Starx

Implementation is correct. But you can cache the results

    var val = this.value;
    $( "#slider" ).slider( "option", "value", val );
    $( "#slider" ).slider( "option", "min", val );
    $( "#slider" ).slider( "option", "step", val );
    $( "#slider" ).slidYou can er( "option", "max", 120 );

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!