Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass object in inline onclick event in dynamically creating elements

I am creating a table row dynamically. Each row is having onclick event. When I click on that table row I want to pass row object to a function but my problem is, while passing that object, I am getting [object object] string. So I am not able to use that object in function.

Please give some solution thanks in advance.

This is my code:

  var row;
  $.each(mydata, function(i,data){
            row+='<tr onclick="myfunction(\''+data+'\')"><td >data.name</td><td >data.age</td></tr>;
    });
 $("#myTable").append(row);
like image 364
harry Avatar asked Oct 31 '22 07:10

harry


2 Answers

I would better use jQuery for defining click event handlers. Here is your updated code:

var $table = $("#myTable");
$.each(mydata, function(i,row){
        $tr = $('<tr>').appendTo($table);
        $tr.on("click", myfunction);
});
like image 98
Timur Osadchiy Avatar answered Nov 12 '22 15:11

Timur Osadchiy


Convert the data object to the following style string.

"{\"name\": \"lenient\", \"age\": 18}" 

Then bind it to the click event, you will get the object as the parameter inside the click function.

like image 44
Lenient Liu Avatar answered Nov 12 '22 15:11

Lenient Liu