S
S
Sergey Burduzha2018-01-27 21:21:10
JavaScript
Sergey Burduzha, 2018-01-27 21:21:10

How to solve "Functions declared within loops referencing an outer scoped"?

Here is my code

let submit = document.querySelector('input[type="submit"]');
let calcCollection = document.querySelectorAll('input[name="calc1"], input[name="calc2"]');
let select = document.querySelector('#sign');
let output = document.querySelector('.output');

submit.onclick = function (e) {
  e.preventDefault();
  let result;
  let sign = select.value;

  if (calcCollection[0].value === '' || calcCollection[1].value === '') {
    submit.setAttribute('disabled', 'disabled');
  } else {
    let calc1 = parseInt(calcCollection[0].value);
    let calc2 = parseInt(calcCollection[1].value);

    switch (sign) {
      case '+':
        result = calc1 + calc2;
        break;

      case '-':
        result = calc1 - calc2;
        break;

      case '*':
        result = calc1 * calc2;
        break;

      case '/':
        if (calc2 > 0) {
          result = calc1 / calc2;
        } else {
          alert('invalid opperation');
        }
        break;
    }

    if (result) {
      output.innerHTML = result;
    }
  }
};

for(let i = 0; i < calcCollection.length; i++){
  calcCollection[i].onkeydown = function(){
    submit.removeAttribute('disabled');
  };
}

The error says that you cannot declare a function in a loop, but how then to hang an event on each element from the collection?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dark Hole, 2018-01-27
@serii81

Can. This is JSLint hinting that such code might be wrong

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question