I'm trying to pass an object to a function in the onclick event. If I run the code below, I get Uncaught SyntaxError: Unexpected indentifier. If I uncomment the JSON.stringify line, and use taskAsJson in place of task, I get the same error.
$.each(tasks, function (index, task) {
//var taskAsJson = JSON.stringify(task);
items.push('<li><a href="#" onclick="showTask(' + task + ');">' + task.Description + '</a></li>');
});
However, if I hard-code a value, like 5, it works and 5 gets passed to the function.
$.each(tasks, function (index, task) {
items.push('<li><a href="#" onclick="showTask(' + 5 + ');">' + task.Description + '</a></li>');
});
Why do I get that error when I try to pass my object? What do I need to change in order to be able to pass task or taskAsJson?
Note: items is an array that gets used to update a div and listview:
$('#appTasks').append(items).listview('refresh');
taskAsJsonin your code? When you write'...' + task + '...', i.e. performing string concatenation, then the objecttaskwill be converted to a string. The default string representation of an object is[object Object], which in your case leads to the string<a href="#" onclick="showTask([object Object]);">. This doesn't look like proper JS, does it?