Reputation: 1
I am trying to pass an array variable to my JavaScript method captureDetails()
. However, it is throwing me error
Uncaught SyntaxError: Unexpected identifier
What am I doing wrong? I tried everything whatever is mentioned in other related posts, but no luck.
if (event.status) {
$("#targetId").empty();
$("#targetId").append("<ul>Please select if this is your organisation</ul>");
for(var i = 0; i < result.length; ++i){
var li = "<li><a href=\"#\" onclick=\"return captureDetails("+result[i]+");\">";
$("ul").append(li.concat(result[i].Name))
}
}
Upvotes: 0
Views: 106
Reputation: 388316
The problem here is the unformatted inline event handler, which creates a invalid syntax.
A more appropriate solution here will be is to use event delegation along with data-*
api to store the data.
//just for testing purpose
var event = {
status: true
},
result = [{
name: 'abc',
id: 1
}, {
name: 'asdf',
id: 2
}]
if (event.status) {
$("#targetId").html("Please select if this is your organisation");
var $ul = $('<ul />');
for (var i = 0; i < result.length; ++i) {
var $li = $('<li />').appendTo($ul);
$('<a />', {
text: result[i].name
}).data('obj', result[i]).appendTo($li)
}
$("#targetId").append($ul)
}
//in dom ready handler
$("#targetId").on('click', 'ul a', function() {
var obj = $(this).data('obj');
snippet.log('clicked on: ' + JSON.stringify(obj));
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="targetId"></div>
Upvotes: 2