Search code examples
javascriptjqueryjquery-ui-slider

jQuery UI Slider custom step increments and comma on load


I'm building a form which uses the "snap to increments" JQuery UI slider: https://jqueryui.com/slider/#steps

This is the code I currently have:

<script>
$(function() {
  $( "#slider" ).slider({
    value:100,
    min: 2501,
    max: 50000,
    step: 500,
    slide: function( event, ui ) {
      $( "#LoanAmount" ).val( '$' + addCommas(ui.value) );
    }
  });
  $( "#LoanAmount" ).val( "$" + $( "#slider" ).slider( "value" ) );

  function addCommas(nStr)
  {
      nStr += '';
      x = nStr.split('.');
      x1 = x[0];
      x2 = x.length > 1 ? '.' + x[1] : '';
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
          x1 = x1.replace(rgx, '$1' + ',' + '$2');
      }
      return x1 + x2;
  }
});
</script>

My first problem is that the code displays the comma for the value only after the slider gets used but not when the page loads. The page loads with the min value of $2501 instead of $2,501

My second problem is that, for compliance reasons, I need the min amount to be $2,501 instead of $2,500 but I still want the step increments to display on the even 500. I need it to be like this: $2,501 > $3,000 > $3,500 > $4,000 > $4,500, until it finishes on $50,000.

Any help will be greatly appreciated. Thanks!


Solution

  • What if you just manipulate the value in the slide event, like this:

    $(function() {
      $( "#slider" ).slider({
          value:100,
          min: 2501,
          max: 50001,
          step: 500,
          slide: function (event, ui) {
            var x = Number(ui.value);
            if (x > 2501) {
                x = x - (x % 500);
            }
            $("#LoanAmount").val('$' + addCommas(x));
          }
        });
            $("#LoanAmount").val( '$' + addCommas($("#slider").slider("value") ) );
    
      function addCommas(nStr)
      {
          nStr += '';
          x = nStr.split('.');
          x1 = x[0];
          x2 = x.length > 1 ? '.' + x[1] : '';
          var rgx = /(\d+)(\d{3})/;
          while (rgx.test(x1)) {
              x1 = x1.replace(rgx, '$1' + ',' + '$2');
          }
          return x1 + x2;
      }
    });
    

    See this jsfiddle for an example: https://jsfiddle.net/bpursley/u1nLma3x/7/