0

Following my code:

HTML:

<input id="test" onkeydown="test();" type="text"/>

JS:

function pl(id){
    return id;
}

function test(){
 id = "test";
 alert(pl(id));   
}

Why the browser return TypeError: test is not a function?

7
  • Maybe your JavaScript is above the HTML? Commented Dec 14, 2013 at 19:34
  • That code won't cause that problem. You appear to have reduced your reduced test case too much. Commented Dec 14, 2013 at 19:37
  • @BenjaminGruenbaum — They are just function definitions, that can't be the problem. Commented Dec 14, 2013 at 19:37
  • @jsve the same... jsfiddle.net/9tFHA/1 Commented Dec 14, 2013 at 19:37
  • 2
    because the fiddle is set to run onload! Change it so the JavaScript is in the head. TADA Commented Dec 14, 2013 at 19:39

1 Answer 1

1

There isn't a problem with the code in the question, but the live example of the code you provided, has your function definitions wrapped in another function (which is executed onload).

They are scoped to their containing function, so you cannot access them with an onclick attribute (which can only touch global variables).

Bind your event handlers programatically instead.

document.getElementById('test').addEventListener(
    "keydown",
    test
    );

For example: http://jsfiddle.net/9tFHA/2/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.