1

Getting error when passing object in onclick event fiddle

(function() { function a() { var x = [{ "name": "main", "data": {"name":'john'} }, { "name": "sub", "data": {"name":'guru'} }, { "name": "lower", "data": {"name":'jack'} }] 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() })() 
3
  • 1
    Check the web-inspector, th html is rendering as onclick="getInfo([object Object])". You should preferably use javascript or jQuery click handlers. Commented Jun 6, 2016 at 6:55
  • 1
    share the getInfo() function. Commented Jun 6, 2016 at 6:55
  • you have to stringify and pass the parameter check this working solution jsfiddle.net/vigneshvdm/fddr0bnv/29 Commented Jun 6, 2016 at 7:20

2 Answers 2

2

You should change way in which your data is generated to this:

var data = "<span onclick='getInfo(" + JSON.stringify(x[i].data) + ")'>main </span>"; 

Without this html that is generated is this:

<span onclick="getInfo([object Object])">main </span> 
Sign up to request clarification or add additional context in comments.

Comments

1

You were trying to assign an object rather its name so that was causing the error. Try it this way

for (var i = 0; i < x.length; i++) { var data = "<span onclick='getInfo(\"" + x[i].data.name + "\")'>main </span>"; data += "<span onclick='getInfo(\"" + x[i].data.name + "\")'>sub </span>" data += "<span onclick='getInfo(\"" + x[i].data.name + "\")'>lower</span><br>" $('#data').prepend(data); } 

Better use Jquery onclick function something like

for (var i = 0; i < x.length; i++) { var data = "<span data-name='\"" + x[i].data.name + "\"' class='notify'>main</span>"; data += "<span data-name='\"" + x[i].data.name + "\"' class='notify'>sub </span>" data += "<span data-name='\"" + x[i].data.name + "\"' class='notify'>lower</span><br>" $('#data').prepend(data); } $(document).on('click', '.notify', function(e) { console.log($(this).attr('data-name')); }); 

Jquery Fiddle

Or as Suggest by @Nemanja Todorovic you can cast Json to string

 for (var i = 0; i < x.length; i++) { var data = "<span data-info='\"" + JSON.stringify(x[i].data) + "\"' class='notify'>main</span>"; data += "<span data-info='\"" + JSON.stringify(x[i].data) + "\"' class='notify'>sub </span>" data += "<span data-info='\"" + JSON.stringify(x[i].data) + "\"' class='notify'>lower</span><br>" $('#data').prepend(data); } $(document).on('click', '.notify', function(e) { console.log($(this).attr('data-info')); }); 

Final Fiddle

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.