kittyhawk
kittyhawk

Reputation: 698

Passing array of objects generated dynamically to onclick handler

I am generating an onclick handler dynamically and setting it using the attr method.

var originReference = "myDynamicString";
var stringArray = [];
stringArray.push("Data1");
stringArray.push("Data2");
var objArray = [];
objArray.push({name: "Category 1", y: 10});
objArray.push({name: "Category 2", y: 20});

onclickReference.attr("onclick", "drawChart('" + originReference + "',[" + stringArray + "],[" + objArray + "]); return false;");

With this code, the objArray is not being passed properly to the handler event as I am getting the error:

"SyntaxError: missing ] after element list".

Using just an array of strings (no JSON). The data is passed to the handler just fine.

How can I format my object array in the onclick handler?

Upvotes: 0

Views: 2034

Answers (2)

gen_Eric
gen_Eric

Reputation: 227200

Don't use onclick attributes to bind events. Use addEventListener to add events.

onclickReference.click(function(){
    drawChart(originReference, stringArray, jsonArray);
    return false;
});

EDIT: According to your comment, you are binding events in a loop. In that case you need to create a closure to "capture" the values of your variables.

Try this:

onclickReference.each(function(){
    // Define your variables inside this new scope
    var originReference = "myDynamicString";
    var stringArray = [];
    var objArray = [];

    this.click(function(){
        drawChart(originReference, stringArray, jsonArray);
        return false;
    });
});

Upvotes: 2

Sharihin
Sharihin

Reputation: 150

You should use JSON.stringify to convert your javascript object to json string.

onclickReference.attr("onclick", "drawChart('" + originReference + "'," + JSON.stringify(stringArray) + "," + JSON.stringify(jsonArray) + "); return false;");

But as @Rocket Hazmat said, use onclick attribute is a bad way to do event binding.

Upvotes: 2

Related Questions