Reputation: 13
I have a JSON file with numerous entries. Below is just 2 of them.
{
"layers": [
{
"name": "Test1",
"id": "Feature",
"subject": "General"
},
{
"name": "Test2",
"id": "Feature",
"subject": "General"
}
]
}
When I run this script and all checkboxes are rendered ok. When I click one of them, I get the output at the console as [object,Object]. Can't see any of properties. I tried the JSON.stringify but no success. Ideas? Thanks.
function XX(){
var mydata = JSON.parse(data)
subjects = []
for (var i = 0; i < mydata.layers.length; i++) {
theID = mydata.layers[i].name
subjects[i] = mydata.layers[i].subject
if (!thecontent[subjects[i]]) {
thecontent[subjects[i]] = '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + mydata.layers[i] + '")\'>'
} else {
thecontent[subjects[i]] += '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + mydata.layers[i] + '")\'>'
}
thecontent[subjects[i]] += '<label for="' + theID + '"> ' + mydata.layers[i].name +
'</label><br>'
}
for (k = 0; k < subjects.length; k++) {
document.getElementById(subjects[k]).innerHTML = thecontent[subjects[k]] + '<br>'
}
}
}
window.loadFL = function (theresponse) {
console.log(theresponse);
}
Upvotes: 1
Views: 1141
Reputation: 19957
When you do this:
thecontent[subjects[i]] += '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + mydata.layers[i] + '")\'>'
or let me mod it into a simpler form, for ease of discussion:
const myInput = '<input onclick=\'loadFL("' + myObject + '")\'>'
You’re concatenating object to string with +
operator. That’ll type-cast object into string type, by implicitly calling myObject.toString()
method (inherited from Object.prototype
) which will return the string "[object,Object]"
.
So if you console.log(myInput)
, you’ll see this:
<input onclick='loadFL("[object, Object]")' >
Above is the explanation.
Below is solution.
If you only need to pass the JSON string value to loadFL
. You can do:
const myInput = '<input onclick=\'loadFL(' + JSON.stringify(JSON.stringify(myObject))+ ')\'>'
You read it right, remove the double quotes "
in the string, and use JSON.stringify
twice.
But if you need to pass the object value, there’s no easy way using HTML string. I’d suggest you use JavaScript to add event listener to HTML node.
Upvotes: 1
Reputation: 61
If JSON.stringify() doesn't work, you can try to print the index of layers like this:
// some code
thecontent[subjects[i]] = '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + i + '")\'>'
// some code
window.loadFL = function (layers_index) {
console.log(mydata.layers[layers_index]);
}
Upvotes: 0