Revamp Your Forms with a Dynamic Range Slider for number inputs

I have added a slider, this not only looks pretty but is very useful if you want your users to only enter between a certain value. This only works with number fields.

For this example I have added percentage but you can have any max values. There is a couple of things you need to do before. This works for both adding and updating records.

  1. Set the ‘max’ value attributes (line 5 Javascript currently 100)
  2. Add your view number where currently ****

Javascript

$(document).on('knack-view-render.view_****', function (event, view, records) {
  $('.kn-input-number').each(function() {
   $(this).find('.control input').hide(); 
    var $inputNumber = $(this);
    $inputNumber.append('<div class="sliderContainer"><div class="slider-value"></div><input type="range" min="0" max="100" value="" id="slider"></div>');
    var $slider = $inputNumber.find('#slider');
    var $inputValue = $inputNumber.find('input');
    var $sliderValue = $inputNumber.find('.slider-value');   
    $inputValue.on('input', function() {
      $inputValue.val($(this).val());
      $slider.val($(this).val());
      $sliderValue.text($(this).val() + '%');
    });    
    if ($inputValue.val() === "") {
      // This will be for an add new record
      $inputValue.attr('value', '0').trigger('input');
      $slider.attr('value', '0');
      $sliderValue.text('0%');
    } else {
      // This will be for a record update
      $slider.attr('value', $inputValue.val());
      $sliderValue.text($inputValue.val() + '%');
    }
  });
});

CSS

.sliderContainer {
  font-size: bold;
  text-align: center;
  font-size: 30px;
}


.sliderContainer #slider{
  width:100%;
}
5 Likes

Looking forward to trying this one out. Thanks @Johnny_Appknowledged_UK.
Your posts are greatly appreciated. :rocket:

1 Like

@CarlHolmes your welcome sir

:exploding_head: awesome!!!

2 Likes