Gergő Sz. - 1 year ago 38

Javascript Question

I am making a little game using multiple range elements to set percentage of a class from the population.

Like,

`<input type="range" id="Miners_r" value="50" min="0" max="100" step="1" >`

<input type="range" id="Farmers_r" value="50" min="0" max="100" step="1" >

How could I prevent setting the others to a higher value than 100% added?

I would like to use js or jquerry to solve this.

`Miner_r.value + Farmers_r.value >= 100`

If something is not clear due to my sillyness, please ask me a question about it!

Thanks in advance!

Answer

It's quite easy. The logic you are looking for is:

- Listen to the change in value of any one of the range element
- Calculate the value allowed for other siblings so that the sum is 100
- Set the other sibling to this value

In my code below, I assumed that there will be use cases where multiple siblings are involved—in that case, the remainder value will be distributed evenly among all the other siblings. It should also work well for your case.

p/s: I have given all your inputs a general class of `.range-group`

just to simply the selection.

```
$(function() {
$('.range-group').on('change', function() {
var $t = $(this),
$s = $(this).siblings('.range-group');
// Cap siblings values to 100 minus the current value.
// The remainder of the values will be distribueted evenly among
// all other siblings.
$s.val(100 - $t.val()/$s.length);
});
});
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" class="range-group" id="Miners_r" value="50" min="0" max="100" step="1" >
<input type="range" class="range-group" id="Farmers_r" value="50" min="0" max="100" step="1" >
```