Search code examples
jqueryjquery-mobile

Setting jquery mobile sliders leads to error


I am trying to set the value of a slider in jQuery mobile 1.4.5, JQ 2.1.4 and do get this error:

Error: no such method 'values' for slider widget instance

HTML Code:

<div data-role="rangeslider" id="filter_price" style="touch-action: none;">
    <input type="range" name="price_from" id="price_from" min="0" max="30000" step="250"  data-popup-enabled="true">
    <input type="range" name="price_to" id="price_to" min="0" max="30000" step="250"  data-popup-enabled="true">
</div>

jquery:

   $('#filter_price').slider();
   $('#filter_price').slider('values', 0,  50);  
   $('#filter_price').slider('values', 1,  100);  

This looks exactly like in the answer provided on SO a few years ago, but might be outdated as it is from 8 years old.


Solution

  • There's a couple of problems here. Firstly you've created some range inputs inside the div you're instantiating the slider on. This is only going to cause problems as they interfere with the slider layout. I'd suggest removing them.

    Secondly, calling values with two arguments is intended to be used with a range slider, not a single value slider. I would assume from the two range inputs you had in the DOM you're attempting to make this a range selection. As such you need to set range: true on the slider when you create it. Then you can call values as you currently are. Try this:

    $('#filter_price').slider({
      range: true,
      min: 0,
      max: 150
    });
    $('#filter_price').slider('values', 0, 50);
    $('#filter_price').slider('values', 1, 100);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
    <div data-role="rangeslider" id="filter_price" style="touch-action: none;">
    </div>

    Also note that if you're attempting to create the slider with these values you can provide all arguments in the instantiation object, without needing to select the element again:

    $('#filter_price').slider({
      range: true,
      min: 0,
      max: 150,
      values: [50, 100]
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
    <div data-role="rangeslider" id="filter_price" style="touch-action: none;">
    </div>