-2

I keep getting this error when trying to use jquery append.

Uncaught SyntaxError: missing ) after argument list

Here is my code:

$(".grid-uniform").append('<input type="checkbox" id="addToCompare-'+prod.id+'" class="addToCompare" onclick="addProductToCompare('+prod.id+','+prod.json.variants[0].id+','+prod.title+')">');

Here are the values being passed in:

addProductToCompare(1557908979773,13234446893117,Apple iPhone X - Zizo ION Triple Layered Hybrid Rugged Case with Tempered Glass, Smoke/Clear)

It looks like the 'with' in the string is getting picked up as JavaScript. It should just be a string. When I check typeof it returns string. If I swap prod.price instead of prod.title though and keep everything else the same, it works fine.

J. Doe
  • 169
  • 10
  • Wasn't this just posted in another question? – epascarello Dec 21 '18 at 23:09
  • do not do it as string https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent – epascarello Dec 21 '18 at 23:11
  • There was an error in the post that caused people to misinterpret it. As a result, no one was able to answer it, and it got erased. So I fixed the error and reposted. – J. Doe Dec 21 '18 at 23:11

1 Answers1

1

It is because you don't make the third argument a string literal, delimiting with quotes.

$(".grid-uniform").append(
    '<input type="checkbox" id="addToCompare-'+prod.id+'" class="addToCompare" ' +
    'onclick="addProductToCompare('+prod.id+','+prod.json.variants[0].id+',\''+prod.title+'\')">'
);

Note the added \' around the last argument.

The better way to do this:

$(".grid-uniform").append(
     $('<input>').attr({type: "checkbox", id: "addToCompare-"+prod.id})
         .addClass("addToCompare")
         .click(function () {
              addProductToCompare(prod.id, prod.json.variants[0].id, prod.title);
         })
);
trincot
  • 317,000
  • 35
  • 244
  • 286