1

I'm on JSFiddle and for some reason the try-catch error message only shows up when the JS code is within the tags in the HTML tab, but when it's in the separate JS tab, the try-catch error won't print.

This would work:

<!DOCTYPE html>
<html>
<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

<script>
function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try { 
    if(x == "")  throw "empty";
    if(isNaN(x)) throw "not a number";
    x = Number(x);
    if(x < 5)  throw "too low";
    if(x > 10)   throw "too high";
  }
  catch(err) {
    message.innerHTML = "Input is " + err;
  }
}
</script>

</body>
</html>

But this doesn't: https://jsfiddle.net/k0rrupt3d/rqejvzoc/

k0rrupted
  • 54
  • 1
  • 7
  • Your function in the fiddle is defined in a different closure. You can try changing the JavaScript pane settings in your fiddle as suggested here: https://stackoverflow.com/a/5468413/4925189. – Caleb Adams Jan 02 '19 at 19:37
  • Your code works fine with codepen: https://codepen.io/anon/pen/mapjKQ – Pingolin Jan 02 '19 at 19:39

1 Answers1

3

It appears that the JS section on the fiddle is locally scoped. If you change your function declaration to window.myFunction = function() { to make it global, it will function as expected.

jmcgriz
  • 2,819
  • 1
  • 9
  • 11