Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: pass an object as the argument to a onclick function inside string

Tags:

I would like to pass an object as parameter to an Onclick function inside a string. Something like follwing:

function myfunction(obj,parentobj){     var o=document.createElement("div");    o.innerHTML='<input type="button" onclick="somelistener(' + obj + ')" />';    parentobj.appendChild(o.firstChild); } 

Obviously, this doesn't work. Anyone has any idea? THX!

A more complete version, as suggested by @Austin

<!DOCTYPE html> <html> <body> <style type="text/css">  </style> <p id="test">test</p> <p id="objectid"></p>  <script> function test(s){     document.getElementById("test").innerHTML+=s; }  function somelistener(obj){     test(obj.id); }  function myfunction(obj,parentobj){      var o=document.createElement("div");     o.innerHTML='<input type="button" onclick="somelistener(' + obj + ')" />';      o.onclick = function () {         someListener(obj)     } parentobj.appendChild(o.firstChild); }  myfunction(document.getElementById("objectid"),document.getElementById("test"));  </script>  </body> </html> 
like image 938
Elizabeth Avatar asked Aug 24 '12 12:08

Elizabeth


People also ask

How do you pass an object on click?

Just stringify the object using JSON. strigify(obj) and pass into the onclick function as parameter and it will be parsed directly and received in the function as Object.

Can you pass an object to a function in JavaScript?

To pass an object to a JavaScript function, we can add a parameter that accepts an object. const someFunc = (arg) => { alert(arg. foo); alert(arg. bar); }; someFunc({ foo: "This", bar: "works!" });

Can you pass an object into a function?

Just as passing objects to functions as arguments is an efficient way of moving information to where it's needed, so is using objects as return values. Functions can either manipulate objects that you pass to them and then return them, or they can return brand-new objects that they create in the function body.


1 Answers

The above example does not work because the output of obj to text is [Object object], so essentially, you are calling someListener([Object object]).

While you have the instance of the element in o, bind to it's click using javascript:

function myfunction(obj,parentobj){      var o=document.createElement("div");     o.innerHTML='<input type="button" />';      o.onClick = function () {         someListener(obj)     }      parentobj.appendChild(o.firstChild); } 

I have created a working fiddle for you here: JSFiddle

like image 180
Austin Avatar answered Sep 21 '22 13:09

Austin