javascriptargument-passing

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


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>

Solution

  • 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