I have a fairly simple question.
The value of my operationVal gets lost when it enters the click event and if(operationVal == 0 ) returns true. But if i check operationVal just before the event it has the selected value. Furthermore, if i write operation.options[operation.selectedIndex].value instead of operationVal in if in the event, the value grabbed is the correct one instead.
I would be grateful if someone explained me why is that so. I'm assuming it has something to do with JavaScript scope, but it doesn't make sense to me.
const firstNumber = document.getElementById('tbFirstNumber');
const secondNumber = document.getElementById('tbSecondNumber');
const operation = document.getElementById('ddlOperation');
const operationVal = operation.options[operation.selectedIndex].value;
const btn = document.getElementById('btnExecute');
const display = document.getElementById('display');
let result = '';
const regNumbers = /[0-9]{1,}/;
btn.addEventListener('click', function(argument) {
if (regNumbers.test(firstNumber.value) && regNumbers.test(secondNumber.value)) {
if (operationVal == 0) {
alert(operationVal);
result = 'Operation has not been chosen';
} else {
switch (operationVal) {
case 'add':
result = 'Result is: ' + (firstNumber.value + secondNumber.value);
break;
default:
// statements_def
break;
}
}
} else {
result = 'Number entry is not correct.';
};
display.innerHTML = result;
});