-1

I am parsing a JSON object and want to make each object as a link and having them be able to call a function when clicked. I then append each of my objects to an unordered list. However, I am getting a syntax error in my code, but I think that the string is built properly. The error states JAVASCRIPT ERROR(unknown source) expected ')'

Any help would be appreciated, thank you!

var string = "<a onclick=AppendDescription(" + obj[i].Name + ")>" + obj[i].Name + "</a>";
//This is what the string looks like after I build it. "<a onclick=AppendDescription(Test 1)>Test 1</a>"

$("#textbox ul").append("<li>"
        + string //error occurs here
        + "</li>");
wheatfairies
  • 355
  • 2
  • 7
  • 19
  • I do not see any error messages related to that line - http://jsfiddle.net/mso7ssz6/, but if `obj[i].Name` has spaces or letters - it could create a problem due to the absence of quotes around the argument of the js function. – Cheery Nov 18 '14 at 23:22

5 Answers5

2

You are missing some quotes. Try this

var string = "<a onclick=\"AppendDescription(\"" + obj[i].Name + "\")\">" + obj[i].Name + "</a>";
damare
  • 201
  • 1
  • 5
1

You are getting nailed by ASI. The parser is inserting a semi-colon at the end of that line. Move your concatenating + operator to the end of the line.

$("#textbox ul").append("<li>" +
    string +
    "</li>");
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
1

It's easier and better practice to attach event handlers in javascript rather than as HTML attributes.

I would do something like this :

$("<li/>").append($('<a href=""></a>').text(obj[i].Name).on('click', function(e) {
    e.preventDefault();
    AppendDescription($(this).text());
})).appendTo("#textbox ul");

Edit

Even better, delegate the click handling to the parent UL.

$("#textbox ul").on('click', 'li', function(e) {
    e.preventDefault();
    AppendDescription($(this).text());
})

for (var i=0; ...) {
    $("<li/>").append($('<a href=""></a>').text(obj[i].Name)).appendTo("#textbox ul");
}
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
0

Check this question, it appears that javascript can't understand multiline without you saying that the string will continue on the next line. It adds an semi-colon at the end like $("#textbox ul").append("<li>"; so he thinks that you are missing an ')'

Community
  • 1
  • 1
0

Unless obj[i].Name is a number, it needs to be within quotes:

var string = "<a onclick=AppendDescription('" + obj[i].Name + "')>" + obj[i].Name + "</a>";
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79