Don’t understand why it only put the first int into array in javaScript



I am want to use a progress bar using Js. So I refer to the online demo. It made by Cassidy Williams on September 13, 2018. Link: https://codepen.io/cassidoo/pen/wEXQaG

When I add more step into steps div elements. Like:

  <div class="steps">
    <div class="step" id="0"></div>
    <div class="step" id="1"></div>
    <div class="step" id="2"></div>
    <div class="step" id="3"></div>
    <div class="step" id="4"></div>
    <div class="step" id="5"></div>
    <div class="step" id="6"></div>
    <div class="step" id="7"></div>
    <div class="step" id="8"></div>
    <div class="step" id="9"></div>
    <div class="step" id="10"></div>
  </div>

When I click the third step. The last step status is clicked. Thus, what is the problem with this error? Also, what is the solution to this error?

Answer

On line 6 of the JS code, the author have the following:

progress(x.target.id);

Replace by:

progress(+x.target.id);

And on lines, 14, 18 and 21, do the same.

steps.forEach((e) => {
    if (+e.id === stepNum) { // <-- here
      e.classList.add('selected');
      e.classList.remove('completed');
    }
    if (+e.id < stepNum) { // <-- here
      e.classList.add('completed');
    }
    if (+e.id > stepNum) { // <-- and here
      e.classList.remove('selected', 'completed');
    }
});

The HTML id is a string, so a cast is necessary. The conditions misbehave because a string comparison is used instead of a number comparison. By casting the string to a number, it is working as intended.



Source: stackoverflow