MariaL
MariaL

Reputation: 1242

Setting jQuery ui slider values dynamically in create event

I'm working on a range slider using jQuery UI slider. As part of this I've got a condition that if the current url contains a specific string it will fire a create event as part of the slider in which I need to dynamically set the values.

This is what my code currently looks like:

<div class="controls">
  <div id="price-range"></div>
  <div class="textinputs">
    <input id="price-min" type="text" value="2"/>
    <input id="price-max" type="text" value="1050"/>
  </div>
</div>

And the JS:

    if (window.location.href.indexOf("min-price") > -1) {
      var url2 = window.location.href;
      var newMinPrice= url2.replace( /[^0-9]/g, '' );
      $('#price-range').slider({
        range: true,
        min: 0,
        max: 1050,
        values: [0, 1050],
        create: function(event, ui){
      $('#price-min').val(newMinPrice);
    },
        slide: function(event, ui) {
          $('#price-min').val(ui.values[0]);
          $('#price-max').val(ui.values[1]);
        },
        change: function( event, ui ) {
          var minPrice = "min-price-" + ($('#price-min').val());
          var maxPrice = "max-price-" + ($('#price-max').val());
          $('.min-price a').text(minPrice);
          $('.min-price a').trigger('click');
        }
      });
    }

So as you can see I'm taking the newMinPrice variable and set the value of input to this. This works fine, but my issue is that while it sets the value for the input correctly, it doesn't update the position of the slider controls to the right point. Anybody know how to do this?

Upvotes: 2

Views: 83

Answers (1)

User863
User863

Reputation: 20039

Try using values option, which set the value for all handles.

Example

$( ".selector" ).slider( "values", [ 55, 105 ] );

$('#price-range').slider({
  range: true,
  min: 0,
  max: 1050,
  values: [0, 1050],
  create: function(event, ui) {
    var minPrice = $('#price-min').val()
    var maxPrice = $('#price-max').val()
    $('#price-range').slider("values", [minPrice, maxPrice]);
  },
  slide: function(event, ui) {
    $('#price-min').val(ui.values[0]);
    $('#price-max').val(ui.values[1]);
  },
  change: function(event, ui) {
    var minPrice = "min-price-" + ($('#price-min').val());
    var maxPrice = "max-price-" + ($('#price-max').val());
    $('.min-price a').text(minPrice);
    $('.min-price a').trigger('click');
  }
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="controls">
  <div id="price-range"></div>
  <div class="textinputs">
    <input id="price-min" type="text" value="100" />
    <input id="price-max" type="text" value="600" />
  </div>
</div>

Upvotes: 1

Related Questions