Home>

We are implementing the score input function with # javascript.
When I enter the score, it is reflected in the total, but when I re-enter it, it becomes NaN.
Currently, there are two times to input the score, and if you correct the second input, it will be NaN, and if you input from the first time, it will be reflected well.
If i make a typo, you will have to retype it from the first time.

Could you please advise me what to improve in the current description to improve it?
Thank you.

# Current description

#javascript
// First time
window.addEventListener ("load", function () {
  let score = document.getElementById ("first-fa-score-field");
  score.addEventListener ("input", function () {
    let first_fa_score = parseInt (score.value);
    let fa_total = document.getElementById ("fa-total");
    fa_total.innerHTML = first_fa_score;
    // Second time
    let second_score = document.getElementById ("second-fa-score-field");
    second_score.addEventListener ("input", function () {
      let second_fa_score = parseInt (second_score.value);
      let fa_total = document.getElementById ("fa-total");
      second_score = (first_fa_score + second_fa_score);
      ## The following input is reflected the first time, but to correct it, you have to start over from the first input.
      fa_total.innerHTML = second_score
})
  })
})

Is it because it is the nesting of the first description in my opinion? I thought.
I tried to describe it without nesting it for the first time, but it didn't work and it was jammed.
Please professor.

  • Answer # 1

    second_score.addEventListener ("input", function () {
          let second_fa_score = parseInt (second_score.value);
          let fa_total = document.getElementById ("fa-total");
          second_score = (first_fa_score + second_fa_score);// No definition for first_fa_score
          fa_total.innerHTML = second_score
    })


    As I wrote in the comment of the above code, there is no definition of first_fa_score.
    Therefore, it seems that (undefined + second_fa_score) = NaN.

    By the way, in the variable definition with let, the variable described in score.addEventListener cannot be used in the function inside it, so you need to define it globally or take other methods such as defining the variable with var. (If it can be used, an error will occur with the declaration of the same name of fa_total.)

Related articles