Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  78] [ 4]  / answers: 1 / hits: 53075  / 13 Years ago, fri, march 25, 2011, 12:00:00

I can't find out what is the problem with this JSFiddle.



HTML:



<input type=button value=test onclick=test()>


JavaScript:



function test(){alert(test);}


And when I click on button - nothing happened. The console says test not defined



I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).


More From » html

 Answers
36

The function is being defined inside a load handler and thus is in a different scope. As @ellisbben notes in the comments, you can fix this by explicitly defining it on the window object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/



$('input[type=button]').click( function() {
alert(test);
});


Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.


[#93077] Thursday, March 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elainaw

Total Points: 83
Total Questions: 99
Total Answers: 111

Location: South Sudan
Member since Sat, May 27, 2023
1 Year ago
;