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>
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.
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!" });
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With