Search code examples
javascriptjqueryrangerangeslidernouislider

noUiSlider: Adjusting rounded input values


When I enter a non-rounded number into the #annual-sales input field, the plugin automatically rounds it up or down, depending on "upper" or "lower". Is there a way for me to enter a specific number into the field such as 1234567 and have it retain that value? Then sliding to the previous or next value would snap it back into place.

<input type="text" id="annual-sales">
<div class="slider-wrap">
  <div class="range-slider-sales-vol"></div>  
</div>

// The first number in the array represents the range. Between the 4 options below I have a range from 1000 - 1000000.
// The second number represents the stepped increments within the given range. From the first to second range the stepped increments are 1000.

var range_all_sliders = {
    'min': [ 1000, 1000 ],
    '33%': [ 100000,  50000 ],
    '66%': [ 500000, 100000 ],
    'max': [ 1000000 ]
};

$('.range-slider-sales-vol').noUiSlider({
    start: [ 1000 ],
    range: range_all_sliders,
    format: wNumb({
        decimals: 0
    })   
});

// Pips plugin for points along range slider
$('.range-slider-sales-vol').noUiSlider_pips({
    mode: 'positions',
    values: [0,33,66,100],
    density: 4,
    stepped: true
});

// links range slider to input
$('.range-slider-sales-vol').Link("lower").to($('#annual-sales'));

Solution

  • This can be done by implementing your own change handler, overriding the one noUiSlider sets by default.

    var annualSales = $('#annual-sales'), guard = false;
    
    function setSalesValue(value){
        if ( guard ) return;
        $(this).val(value);
    }
    
    annualSales.change(function(){
        var value = $(this).val();
    
        guard = true;
        slider.val(value);
        guard = false;
    });
    
    // links range slider to input
    $('.range-slider-sales-vol').Link("lower").to(annualSales, setSalesValue);
    

    Notice the use of a guard variable: it prevents the slider from updating the input with the value set in the change handler.

    I've updated your code with a working example. Try changing the input field; the slider will update, the input value won't be reset. Moving the slider will update the input.