SanyamMishra SanyamMishra - 4 months ago 21
Javascript Question

Uncaught TypeError: lang is not a function

Code



<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Testing Functions</title>
<script type="text/javascript">
function lang() {
alert("Hello, World! It's JavaScript this time");
}
</script>
</head>

<body>
<form action="">
<input type="button" value="Test Fire!" onclick="lang();">
</form>
</body>

</html>





If I click on "Test Fire!" button I get this error:


Uncaught TypeError:
lang
is not a function


But if I change the function name from
lang
to anything else this code works fine.

Answer

Consider this code:

<input type="button" value="Test Fire!" onclick="debugger;" />

When you open your debugger, you’ll see that there seems to be an implicit with scope wrapped around the onclick, making all the <input>’s properties accessible without needing to refer to the button.

This means that all global attributes (lang is one of them) and several others specific to buttons are overridden. E.g. value, type also wouldn’t work.

Your best bet is to use the standard way of adding event listeners: addEventListener.

<input type="button" value="Test Fire!" />
<script>
  function lang() {
    alert("Hello, World! It's JavaScript this time");
  }
  document.querySelector("input").addEventListener("click", lang);
</script>

Comments