Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function is undefined on onclick event of anchor tag

I am not able to access javascript function in onclick event of the anchor tag.

In some cases it is working and in some cases , not.

Can any body tell why it is happening.

HTML CODE -

<a  href='#'  class="btn waves-effect waves-light bg-blue" id="startDeviceScan" onclick="call286Dart123('CollectSysInfo', '3c6c3e33bb65e8331bf4c91c0670492e');" >start device scan </a>

Javascript function :

function call286Dart123(a,b) {
    console.log(a + "\t" + b);
}

Fiddle link

Fiddle Link

like image 735
Dhananjay Jadhav Avatar asked Jul 14 '16 11:07

Dhananjay Jadhav


Video Answer


2 Answers

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):

<script type="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):

<script type="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.

like image 92
Jonathan Lam Avatar answered Sep 28 '22 08:09

Jonathan Lam


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

JSBin example

like image 26
Mike W Avatar answered Sep 28 '22 06:09

Mike W