Search code examples
jqueryjquery-uiuislider

jquery ui slider storing value in a var


hey I have a slider set up using jquery ui, and for some reason I can't get the basic set up of having a slider, range 1-3, and then when the slider is moved having that current value displayed in a div, for some reason the numbers it displays aren't in order 1,2,3.

I have a fiddle here:

http://jsfiddle.net/vG8NY/14/

code is as follows:

html:

<div id="variable_slider"></div>
<div id="slide"></div>

js:

 $("#variable_slider").slider({
     value: 2,
     range: "min",
     min: 1,
     max: 3,
     step: 1,
     slide: function (event, ui) {
         slider_value = $("#variable_slider").slider("value");
         $("#slide").html(slider_value);
     }
 });

Solution

  • Try using

     $("#variable_slider").slider({
         value: 2,
         range: "min",
         min: 1,
         max: 3,
         step: 1,
         slide: function (event, ui) {
             slider_value = ui.value;
             $("#slide").html(slider_value);
         }
     });
    

    Whereas the important part is:

    slider_value = ui.value;
    

    Why?

    ui is already providing a reference to your slider object, and its property .value contains the correct value.

    See this page for an example implementation.