I've encountered an issue with the try, catch, and throw in my code. The outcome I'm seeing is not what I expected. Here's the problem: when I enter a number greater than 5 into the form field, nothing is displayed instead of "too high." But when I enter numbers less than 5, it shows "too high" instead of "too low." Additionally, most of the other if conditions don't seem to be working as intended except for empty and too high. Can anyone shed light on this anomaly?
function myFunction() {
var x, message;
message = document.getElementById('para');
message.innerHTML = '';
x = document.getElementById('formField').value;
try {
if (x == "") throw 'empty';
if (isNaN(x)) throw 'not a number';
x = Number(x);
if (x < 5) throw 'too low';
if (x > 5) throw 'too high';
}
catch(err){
message.innerHTML = 'input is ' + err;
}
}
It seems like many people are struggling to grasp my issue here. This code was directly copied from W3schools, but it's not functioning correctly. The various if statements are meant to trigger specific errors when the input value meets certain conditions. However, they are producing unexpected results. For example, entering just 2 triggers "input is too high" instead of "too low." Entering numbers above 5 doesn't trigger any error, and there is no response from JavaScript for NaN.
If anyone can comprehend what I'm trying to convey, please run the code yourselves and help me understand where I might be mistaken.