0

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))
    }
} 
2
  • 1
    what is the value of result? Commented Jul 9, 2015 at 3:03
  • You are already using jQuery, why are you using inline javascript instead of [click()](api.jquery.com/click). Plus a class name to your anchors and a data attribute holding i and simply done. Commented Jul 9, 2015 at 3:16

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This is very very elgant, just what I explained in comment but put professionnaly. Thank you plus one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.