How to get the index of the tickmarks of an input type=range?

168 Views Asked by At

I am having a input type=range and need to know which tickmark index my slider has to get some values out of an array.

var slider = document.getElementById("myRange"); 
var output = document.getElementById("output"); 
var repaymentsInfo = document.getElementById("repayments"); 
var requiredIncome = document.getElementById("income"); 
var ticks = document.getElementsByTagName("option");


var repayList = [];
var incomeList = [];


for (var i = 0; i < ticks.length; i++){
    repayList.push(data[i].repaymentsPerMonth)
    incomeList.push(data[i].requiredAnnualIncome)
}

slider.oninput = function(){
output.innerHTML = this.value;
repaymentsInfo.innerHTML = repayList[**index**];
requiredIncome.innerHTML = incomeList[**index**];
};
slider.oninput();`

I tried all the possible attributes of slider.oninput, but I can't find the solution how to extract the current index of my slider point.

2

There are 2 best solutions below

2
On
slider.oninput = function() {
  const i = data.findIndex(({ propertyValue }) => propertyValue == this.value);
  output.innerHTML = this.value;
  repaymentsInfo.innerHTML = repayList[I]
  requiredIncome.innerHTML = incomeList[i]
};
slider.oninput()
3
On

I think you can calculate it. Try running the snippit - it shows how. if you wanna fiddle:https://jsfiddle.net/Phiddle/z0xw2eoL/54/

var slider = document.getElementById("myRange");
var output = document.getElementById("output");
var index = document.getElementById("index");
var tickIndex = document.getElementById("tickIndex");
var tickValue = document.getElementById("tickValue");

var ticks = ['First', 'Huhu', 'Jaja', 'Gugu', 'Yoooo', 'Last'];

const steps = 17;
const amountEachStep = 150000;
const maxValue = amountEachStep*steps;
const amountPerTick= maxValue/(ticks.length-1)

slider.max = maxValue;
slider.step = amountEachStep;

slider.oninput = function(){
  output.innerHTML = this.value;
  index.innerHTML = this.value/this.step;
  tickIndex.innerHTML = Math.round(this.value/amountPerTick);
  tickValue.innerHTML = ticks[Math.round(this.value/amountPerTick)];
};
slider.oninput();
input {
    display: block;
    width: 100%;
}
<input id="myRange" type="range" />
<div>Value:</div>
<div id="output"></div>
<div>Step:</div>
<div id="index"></div>
<div>Tick Index:</div>
<div id="tickIndex"></div>
<div>Tick Value:</div>
<div id="tickValue"></div>