timrosenthal
timrosenthal

Reputation: 57

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>

Upvotes: 0

Views: 1117

Answers (2)

rbntd
rbntd

Reputation: 391

@Dave Gomez answers is way more elegant, please use it instead. But if you are wondering why it wasn't working :

Your document.getElementById("cuts").value; return strings. You need to convert them to int before adding them. This can be done like this :

a = +document.getElementById("cuts").value;
b = +document.getElementById("burns").value;
... etc

Upvotes: 0

David Gomez
David Gomez

Reputation: 2772

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

Upvotes: 3

Related Questions