Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 input type range - non-linear sequence?

I want to use a slider control to input a selection. The possible values are: 5000, 25000, 50000, 75000, and 100000. However, I cannot get the range input to limit to those choices. The closest thing I've got is this:

<datalist id="valid-options">
  <option>5000</option>
  <option>25000</option>
  <option>50000</option>
  <option>75000</option>
  <option>100000</option>
</datalist>
<input type="range" min="5000" max="100000" step="5000" list="valid-options" ng-model="selectedValue" />

You can see the full sample here: http://jsfiddle.net/au14Lv2t/1/

The problem with this solution is that it allows for invalid values like 10000, 15000, etc.

I'm looking for an AngularJS (or pure HTML5/JS/CSS) solution. I would prefer not to introduce jQuery.

Thanks!

like image 680
dprothero Avatar asked Sep 30 '22 12:09

dprothero


2 Answers

you can search for the closest valid value and set the input value to that value for each value change event

var inputElement = document.getElementById('customRangeInput');

inputElement.oninput = setInput;
inputElement.onchange = setInput;   // IE fix

function setInput(){
    inputElement.value = closestValue(inputElement.value);
}

var validValues = [5000,25000,50000,75000,100000];
function closestValue(input)
{
    var differences = [];
    for (var i = 0; i < validValues.length; i++)    
        differences.push( Math.abs(validValues[i] - input));

    var index = indexOfSmallest(differences);
    return validValues[index];      
}

function indexOfSmallest(inputArray) {
    var lowest = 0;
    for (var i = 1; i < inputArray.length; i++) {
        if (inputArray[i] < inputArray[lowest]) lowest = i;
    }
    return lowest;
}

html should look like this

<input id="customRangeInput" type="range" min="5000" max="100000" step="5000" list="valid-options" ng-model="selectedValue" />Selected Value: {{ selectedValue }}</div>
like image 70
Alper Cinar Avatar answered Oct 03 '22 10:10

Alper Cinar


you need to use property step, that let's you decide how much is every step, for your example, most values are in 25000 so make step="25000"

<input type="range" min="0" max="100000" step="25000">

and to solve the 5000 value... in your example your first value is 5000 what you do is that if you receive 0 that is your low value that is 5000... the other values increase in 25000... hope that helps.

and you don't need the datalist in this case.

like image 37
xploshioOn Avatar answered Oct 03 '22 09:10

xploshioOn