Javascript Function Is Undefined On Onclick Event Of Anchor Tag
Solution 1:
EDIT Due to what @Dellirium pointed out in the comment, I've revised my answer to reflect the true issue here. The solution would still work, however.
The problem is that JSFiddle makes the JavaScript run on document load by default. This means that the JS is loaded after the HTML, and therefore it wouldn't have been defined at the time the onclick
event was initialized in the HTML.
It seems to be a problem with closures. If you have "Load Type" set to "onload" in JSFiddle, this is what it does internally (you can check the developer console):
<scripttype="text/javascript">
//<![CDATA[
window.onload=function(){
function call286Dart123(a,b) {
console.log(a + "\t" + b);
}
}
//]]>
</script>
This means that it is wrapped in in an anonymous event handler to the onload
event. And since variable (and function) scopes are bound by functions in JavaScript, this makes them not available to the global scope
Solution: To fix this, under the "JavaScript" menu, change "Load Type" to "No wrap - in &t;head>". It's that easy =).
See this JSFiddle fork as a working example.
In other words, this would simply change it to (again, you can verify this by visiting the developer console on my JSFiddle):
<scripttype="text/javascript">
//<![CDATA[
function call286Dart123(a,b) {
console.log(a + "\t" + b);
}
//]]>
</script>
In which, cal286Darkt123
would be defined in the global scope (outside any other functions).
For more info on closures, check the MDN Docs.
Solution 2:
Don't use onclick attribute to run JavaScript if you can help it. Instead use event listeners or JQuery on method.
<a id="startDeviceScan">Do Something</a>
Vanilla JS:
<script>var el = document.getElementById("startDeviceScan");
el.addEventListener("click", your_func, false);
</script>
JQuery:
$( "#startDeviceScan" ).on( "click", your_func(1234));
If you need to fetch an elements attributes for the argument such as the '1234' you can use data- attributes and reference them with JS or JQuery
Solution 3:
Works for me :
<script>functioncall286Dart123(a,b) {
console.log(a + "\t" + b);
}
</script><aclass="btn waves-effect waves-light bg-blue"id="startDeviceScan"onclick="call286Dart123('CollectSysInfo', '3c6c3e33bb65e8331bf4c91c0670492e');"href='#' >start device scan </a>
Post a Comment for "Javascript Function Is Undefined On Onclick Event Of Anchor Tag"