29

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>
Elizabeth
  • 491
  • 1
  • 4
  • 9
  • @Austin I am not sure if I understand your answer correct. But as I tried in complete version above, it does not work either. Could you see the problem? – Elizabeth Aug 26 '12 at 12:38
  • @scott.korin Thx Scott. But after I changed the capitalization, it still does not work. – Elizabeth Aug 26 '12 at 12:57
  • @Austin BTW, even if I change o.onclick to o.firstChild.onclick, that does not work either, if that is potentially a problem. – Elizabeth Aug 26 '12 at 13:05
  • Can you be a little more specific? What exactly is not working? – Austin Aug 27 '12 at 11:29
  • Should work fine, see my jsfiddle [here](http://jsfiddle.net/RDVHr/) – Austin Aug 27 '12 at 11:38
  • Got it, thx! Does that mean there is no way to declare onclick function with obj as parameter inside the string? – Elizabeth Aug 27 '12 at 15:15
  • No problem, be sure to click the check next to my answer if you feel I best answered your question. And no, there is no _efficient_ method to do it the way you originally tried. – Austin Aug 27 '12 at 16:06

5 Answers5

26

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

Austin
  • 6,026
  • 2
  • 24
  • 24
11

Old question whose answers I didn't quite understand, but the simplest solution is to combine the functions encodeURIComponent and JSON.stringify, that is, you stringify the object and then escape those special characters, and then reverse the process inside the function

var obj = {a: 'hey there', b: 1}

document.getElementById('mydiv').innerHTML =
  `<button onclick="myFunction('${encodeURIComponent(JSON.stringify(obj))}')">Click me</button>`

function myFunction(obj) {
  console.log(JSON.parse(decodeURIComponent(obj)))
}
<div id="mydiv"></div>
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
10
function myfunction(obj,parentobj){ 
        var o=document.createElement("div");
         o.innerHTML="<input type='button' onclick='somelistener("+JSON.stringify(obj)+")'/>"; 
                                  parentobj.appendChild(o.firstChild);
            } 
    // my similar problem, function a was called in a jsonArray loop in the dataTable initiation
    function a(data, type, obj) {
                         var str = "";
                         str += "<span class='button-group'>";
                         str +="<a onclick='chooseData1("+JSON.stringify(obj)+")'>[选择]</a>";
                         str += "</span>";
                         return str;
                                            }
function chooseData1(data){
                        console.log(data);
                  }
Nikikiy SCC
  • 111
  • 1
  • 4
3

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.

function myfunction(obj,parentobj){ 
   var o=document.createElement("div");
   var stringifiedObj = JSON.stringfy(obj)

   o.innerHTML='<input type="button" onclick=`somelistener(${stringifiedObj})` />';
   parentobj.appendChild(o);
}

function somelistener(obj){
   console.log(typeof obj) //Object
}
HaRish. P
  • 31
  • 2
-9

Just do pass it like this :

o.innerHTML='<input type="button" onclick="somelistener(this)" />';
Jaskaran Singh
  • 2,392
  • 24
  • 39
  • 1
    Passing 'this' won't work. The object passed is definitely *not* identifiable by 'this'. Downvoted. –  Jun 13 '15 at 14:35