zxue zxue - 4 months ago 30
jQuery Question

SyntaxError: missing ] after element list when try to pass object parameter to onclick function

I am trying to iterate a list of objects, and create a list item for each of them with as a button. When I add

onclick
function to them. I got this error:


SyntaxError: missing ] after element list


Here is my code:

box_resources.forEach(function(box){
$("#box-resources-list").append('<li><button type="button" class="list-group-item" onclick="showBoxMarker(' + box + ')">' + box.title + '</button></li>');
});


Any idea on it? Thanks!

Answer

The problem is that box is converted to a string when you're creating elements like that. For example:

var box = {
  x: 10,
  y: 10,
  w: 5,
  h: 3
};
console.log('onclick="showBoxMarker(' + box + ')"');

Obviously, calling showBoxMarker([object Object]) isn't valid syntax. Instead, you should create the elements separately then attach an event handler to that element.

box_resources.forEach(function(box){
    var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>');

    // Find the button we just made and attach the click handler
    $listItem.find('button').click(function() {
        showBoxMarker(box);
    });
    $('#box-resources-list').append($listItem);
});

Working example:

var showBoxMarker = function(box) {
  alert(box.title);
}

var box_resources = [
  { title: 'Box A' },
  { title: 'Box B' },
  { title: 'Box C' },
  { title: 'Box D' },
  { title: 'Box E' }
];

box_resources.forEach(function(box){
  var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>');

  // Find the button we just made and attach the click handler
  $listItem.find('button').click(function() {
    showBoxMarker(box);
  });
  $('#box-resources-list').append($listItem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="box-resources-list"></ul>

Pro-tip: In general, it's better to create new elements from some kind of template instead of from strings in JS and create one click handler on a parent element and use event delegation to handle click events on individual elements.