timrosenthal timrosenthal - 1 month ago 11
Javascript Question

How to group together HTML5 Range Slider values?

Is there a way to group together multiple html5 slider fields. Originally I tried doing this will

type=number
fields but I didn't like the way it looked.

So what I what I have is 7 fields that I want to use sliders with individual min values of 0 and max values of 100 - however - the trick is that I need a way to add them all up to make sure in total they equal 100. None of the fields individually are required. Does that make sense?

Here is the function I tried but its not working at all:

<script>
function percentageTest() {

// Get the value of the input fields
a = document.getElementById("cuts").value;
b = document.getElementById("burns").value;
c = document.getElementById("infection").value;
d = document.getElementById("dermatitis").value;
e = document.getElementById("puncture").value;
f = document.getElementById("sprain").value;
g = document.getElementById("impact").value;

var x = (a + b + c + d + e + f + g);

// grouping together and doing the math
if (x != 100) {
text = "The total percentage must equal 100%";
}
document.getElementById("rec_injuries").innerHTML = text;
}
</script>

Answer

You can do something like this (just make it pretty and adapt it to your needs):

HTML

<form>
  <formgroup class="ranges">
    <input type="range" min="0" max="100">
    <input type="range" min="0" max="100">
    <input type="range" min="0" max="100">
    <input type="range" min="0" max="100">
  </formgroup>
</form>

JavaScript

var ranges = Array.from(document.querySelector('.ranges').children);

var total = ranges.reduce(function(acc, curr) {
  return acc + Number(curr.value)
}, 0)

// Now you can check total