-2

I am working on some kind of calculator, and lets say i have a global variable called IQ. Now, I have a checkbox with 5 options (in this case 5 different persons). I want each person to either reduce or increase the global variable IQ when they are selected.

I thought about doing this with if statements, but what if the first if is true(i.e one person is checked and value === person). Then the code would stop right and not check the other if-statements to see if more persons/checkboxes are selected. Hope this is clear what i ment.

This is my HTML-code:

<input type="checkbox" name="person" value="frank"> Frank Aarebrot<br>
<input type="checkbox" name="person" value="gaben"> Gabe Newell<br>
<input type="checkbox" name="person" value="lance"> Lance Armstrong<br>
<input type="checkbox" name="person" value="trond"> Trond Kirkvaag<br>
<input type="checkbox" name="person" value="davy"> Davy Wathne<br>
Joachim Morken
  • 311
  • 1
  • 2
  • 10
  • the only way it wouldn't check the other if statements is if you combined them all into a large if-else block. if you had each if statement separated, it would still evaluate each if statement. If you have tried javascript code that could illustrate the problem you're running into, you should add it into the question. You have javascript tagged because you are going to write javascript, but you really should have an attempt in your question. – Lexi Jun 05 '17 at 19:58
  • Possible duplicate of [Get the value of checked checkbox?](https://stackoverflow.com/questions/11599666/get-the-value-of-checked-checkbox) – Code4R7 Jun 05 '17 at 20:04

1 Answers1

0

You can listen to change event on each checkbox and calculate your number accordingly. Here I create a new map-like object with person name as a key and +-1 as a value to indicate weither to add or subtract 1:

var cbs = document.querySelectorAll('input[type=checkbox][name=person]');

var plusMinus = {
  frank: 1,
  gaben: -1,
  lance: 1,
  trond: -1,
  davy: 1
}

var p = document.getElementById('iq');
p.textContent = '0';

for (const cb of cbs) {
  cb.addEventListener('change', (e) => {
    var {checked, value} = e.target;
    p.textContent = parseInt(p.textContent) + plusMinus[value]
      * ((checked) ? 1 : -1) // +- math
  })
}
<input type="checkbox" name="person" value="frank"> Frank Aarebrot<br>
<input type="checkbox" name="person" value="gaben"> Gabe Newell<br>
<input type="checkbox" name="person" value="lance"> Lance Armstrong<br>
<input type="checkbox" name="person" value="trond"> Trond Kirkvaag<br>
<input type="checkbox" name="person" value="davy"> Davy Wathne<br>
<hr>
<p id="iq"></p>
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35