I want to change range value as per given custom value in screen shot. Right now I'm getting 1,2,3,4,5,6 values onchange of range but I need 6,12,24,36,48,60 values. How can I do this?
My Code:
<div >
<input type="range"min="1" max="6" steps="1" value="1" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
</script>
ThankYou for your efforts!
CodePudding user response:
You can take a array and store the values you need in your slider.
<div >
<input type="range"min="0" max="5" steps="1" value="0" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<script>
var values = ["6 mo","12 mo","24 mo","36 mo","48 mo","60 mo"];
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
slider.oninput = function(){
output.innerHTML = values[this.value];
};
slider.oninput();
</script>
CodePudding user response:
The below snippet solves your problem
Changing this.value to set values in an array
<div >
<input type="range"min="1" max="6" steps="1" value="1" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<script>
values = [6,12,24,36,48,60];
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = values[this.value-1];
}
</script>
CodePudding user response:
If you have a fixed range you can use this method.
<div >
<input type="range"min="1" max="6" steps="1" value="1" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value === "1" ? '6 mo' : slider.value;
function myFunction(pos) {
const myMonths = [6, 12, 24, 36, 48, 60]
return myMonths[pos - 1] ' mo'
}
slider.oninput = function() {
output.innerHTML = myFunction(this.value);
}
</script>
CodePudding user response:
You can just use min
, max
, and step
attributes to control the range of slider, without any need of JavaScript.
Also, There's a typo in your code. The name of attribute is step
not steps
.
<div >
<input type="range" min="6" max="60" step="6" value="6" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
</script>
If you want "mo" after the value, you can just do output.innerHTML = this.value "mo";