Search code examples
jqueryarraysrangeslider

How to access to the current range slider?


I have 2 range inputs (say 100) and want to attach the values of each one to an array e.g.:

   <input id="range1" type="range" max="2">
   <input id="range2" type="range" max="2">

    <script>
    var items=new Array();

    items[1]=new Array("dog","horse","cat");
    items[2]=new Array("x","y","z");

    for (x=1;x<3;x++){
        $('#range'+x).rangeslider({
            polyfill : false,
            onSlideEnd: function(position, value) {
                console.log(items[x][value]);       
            }
        });
    }
    </script>

The current logic always prints items[2][blah] value because at the end of loop the x=2. How can I access the current input inside the rangeslider (So extract its ID) (or possibly create a local variable rather than x inside that loop for each slider to get rid of the global variable X)?


Solution

  • You can get the element and the current value in the onSlideEnd event like this

    $(document).ready(function() {
      // you can also use $('*[id^="range-"]').rangeslider({
      $('.range-slider').rangeslider({
        polyfill: false,
        onSlideEnd: function(position, value) {
          // access to the range-input: this.$element
          // the example shows the id of the range element
          console.log(this.$element.attr('id'));
          
          // access to the current value
          console.log(value);
        }
      });
    });
    .rangeslider { margin-bottom: 35px; }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.3/rangeslider.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.3/rangeslider.min.js"></script>
    
    <input id="range-1" class="range-slider" type="range" max="2" />
    <input id="range-2" class="range-slider" type="range" max="2" />
    <input id="range-3" class="range-slider" type="range" max="2" />