Le Qs Le Qs - 1 month ago 6
Javascript Question

strange unexpected token that does not exist

I have this fiddle that I am trying to append some rows into a table. This is the code:

$(document).ready(function () {
$(document).on('click', '.btn-primary', function(){
$('.table tbody').append('<tr class="child"><td>one</td><td><button id="re" onClick="ae(this.id); function ae(clicked_id) {var items = []; items.push(clicked_id);localStorage.setItem("item",JSON.stringify(items));alert(localStorage.getItem("item",JSON.stringify(items)));}" type="button" class="invite ">Invite</button></td></tr>');
});
});


I can generate the rows but I keep getting an error saying that I have a brace that does not belong there. The problem is the brace is not even there.


VM140:2 Uncaught SyntaxError: Unexpected token }


Don't ask why I have an
onclick
as an event handler when there is jQuery. I have my reasons for the example. Why am I getting this error?.

Answer

you have problems with quotes inside quotes, I've changed .setItem("item"... to .setItem(\'item\' and also for getItem and it works now

 $(document).ready(function () {
     $(document).on('click', '.btn-primary', function(){
         $('.table tbody').append('<tr class="child"><td>one</td><td><button id="re" onClick="ae(this.id); function ae(clicked_id) {var items = []; items.push(clicked_id);localStorage.setItem(\'item\',JSON.stringify(items));alert(localStorage.getItem(\'item\',JSON.stringify(items)));}" type="button" class="invite ">Invite</button></td></tr>');
      });
 });