1

I am trying to bind a function through onclick attribute but I m getting the function undefined error. fiddle

(function() {
  function getInfo(x) {
    console.log(x)
  }

  function a() {
    var x = [{
      "name": "main",
      "data": ['1', '2', '3']
    }, {
      "name": "sub",
      "data": ['4', '5', '6']
    }, {
      "name": "lower",
      "data": ['7', '8', '9']
    }]
    for (var i = 0; i < x.length; i++) {
      var data = "<span onclick='getInfo(" + x[i].data + ")'>main </span>";
      data += "<span onclick='getInfo(" + x[i].data + ")'>sub </span>"
      data += "<span onclick='getInfo(" + x[i].data + ")'>lower</span><br>"
      $('#data').prepend(data);
    }


  }
  a()
})()
4
  • 1
    You've hidden the getInfo() function inside the IIFE function. Move it outside to be global so that the handlers can find it. Commented Jun 6, 2016 at 0:42
  • 1
    You are silently casting x[i].data which is an array into a string, this will most likely give unexpected results Commented Jun 6, 2016 at 0:49
  • @WalleCyril: you are right. Can you please tell me how to fix this problem. Commented Jun 6, 2016 at 2:17
  • JSON.stringify could do the trick: "<span onclick='getInfo("+JSON.stringify(x[i].data)+")'>main </span>" Commented Jun 6, 2016 at 9:56

1 Answer 1

1

I think the reason you get undefined is because the onclick will try to find the function in the global scope, while your getInfo function is defined within a function scope.

Then you should make getInfo a property of the global scope (window) to fix the issue. For example:

window.getInfo = function(x) {
    console.log(x)
}

See the updated fiddle.js here: https://jsfiddle.net/fddr0bnv/6/

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

5 Comments

Can you explain why a normal function won't work here? I mean, why window.getInfo = function(x) works and function getInfo(x) doesn't?
I think I kind of explained in my answer. The way I think of it is that the inline event handlers can only find a function in the global scope. (this may be a limitation in browsers?) - There are better ways to attach an onclick event to an element, for example using addEventlistener more is explained here: w3schools.com/jsref/event_onclick.asp
@Filype: Why window.getInfo work when function getInfo did not even if we put the function getInfo on global scope
@Carlos, I am pretty sure it would work if the function is placed in the global scope with the same name. To try this I would suggest a script tag inside your HTML with only the function. I am pretty sure this will have the same effect.
@Carlos I have updated the fiddler with the function in the global scope: jsfiddle.net/fddr0bnv/7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.