1

I am trying to get the selected value from the Ion Range slider outside the function. But the value I am getting is undefined. I used the Ion range Slider Plugin with the following code.

  function getValue()
  {
  $(".range-slider").ionRangeSlider({
       // type: "single",
        min: 80,
        max: 100,
        grid: true,
      
       onFinish: function (data) {
            // Called every time handle position is Finished
          var value = data.from;
        return value;
 //         console.log("Confidence: ",confidence);
     }
    });
    } 
    
    getValue();
    
    console.log("Value", getValue());

I can't figure out how can I get the range selected value outside the function. Here is the fiddle that I have tried: https://jsfiddle.net/georgoboy/kxcmagjw/1/

Bunty Sharma
  • 104
  • 12

2 Answers2

0

If you want to retrieve the initial value of the range slider you can use:

console.log("Value",  $(".range-slider").val());

The onFinish()-Function should be used to respond to changes from user.

Tbi
  • 154
  • 10
0

The value of the slider is only known after the slider is moved by the user. When that happens, the onFinish callback is called. Then, the value is passed as an argument to that function.

In order to get it out of that callback, you can change some kind of a global variable inside of onFinish, like this:

// This is where the updated value will be stored.
let currentValue = 0;

  $(".range-slider").ionRangeSlider({
       // type: "single",
        min: 80,
        max: 100,
        grid: true,
      
       onFinish: function (data) {
            // Called every time handle position is Finished
          var value = data.from;
          // Value is available here
          console.log("Value", value);
          currentValue = value;
 //         console.log("Confidence: ",confidence);
     }
    });

That would not be useful however, because you can't really tell when it changes and so can't run any code afterwards. The better option would be to use the "reactive" approach: call function sliderValueUpdated after each update and do stuff there.

const sliderValueUpdated = (newValue) => {
  // Do something with the updated value here
  console.log("Value", value);
  // console.log("Confidence: ",confidence);
};

...
       onFinish: function (data) {
          // Called every time handle position is Finished
          var value = data.from;
          // Value is available here
          sliderValueUpdated(value);
     }
...

And you can call the update function right after initialization in order to account for the initial value:

sliderValueUpdated($(".range-slider").val());
comonadd
  • 1,822
  • 1
  • 13
  • 23