Uncaught TypeError: lang is not a function

In my HTML, I define the lang function in the script tag and add "Test Fire!"., Which should call lang when clicked:

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Testing Functions</title> <script type="text/javascript"> function lang() { alert("Hello, World! It JavaScript this time"); } </script> </head> <body> <form action=""> <input type="button" value="Test Fire!" onclick="lang();"> </form> </body> </html> 

However, if I click the button, I will get this error:

Uncaught TypeError: lang not a function

But if I change the function name from lang to something else, this code will work fine.

+8
javascript uncaught-typeerror typeerror
source share
2 answers

Consider this code:

 <input type="button" value="Debugger Test" onclick="debugger;" /> <input type="button" value="Prototype Test" onclick="console.log(__proto__);" /> 

When you click on the โ€œDebugger Testโ€ and open your debugger, you will see that there appears to be an implicit with scope wrapped around onclick , which makes all the <input> properties available without having to reference the button.

Clicking on the "Prototype Test" will register the prototype of the current area. You will see that this is an HTMLInputElement prototype, which makes all the properties available for defining this entire prototype chain available to the scope.

It is interesting to note that the included prototype portion of the current HTMLDocument chain HTMLDocument also included.

All this means that all global attributes ( lang is one of them) and some others, specific to buttons, are redefined. For example. value , type will not work either. Similarly, variables such as createElement (from document ) will not work either, but an non-copyable append (from ParentNode.prototype ) will.

All of this is also explained in this answer to a related question about global variables that conflict with window properties.


It is best to use the standard way to add event listeners: addEventListener .

 <input type="button" value="Test" /> <script> function lang() { alert("Hello, World! Its not an HTML event handler attribute this time"); } document.querySelector("input").addEventListener("click", lang); </script> 

+6
source share

There is no reason to complicate things (I really don't know why this does not work), but you can use:

  • Add an alert directly to the entrance.

Result: https://jsfiddle.net/cmedina/h4m1qcoq/6/

or

Add Listener for Input

 function lang() { alert("Hello, World! It JavaScript this time"); } document.getElementById('test').onclick = lang 

Result: https://jsfiddle.net/cmedina/h4m1qcoq/7/

+2
source share

All Articles