Skip to content
Advertisement

jQuery append onclick

I’m append html code using jquery append function. If on onclick I use function with one parameter – all right, but if I use function with multiple parameters I get error in console: SyntaxError: missing ) after argument list. My code:

var quote = quotes[i];
$('#quu').append('<div onclick="addBook('+quote.userId+', '+quote.book+')">'+quote.book+'</div>')

Function addBook:

function addBook(user_id, name) {
   alert(name);
   alert(user_id);
}

What I’m doing wrong?

Advertisement

Answer

You need to add quotes to the name quote.book since it shall be passed as a string parameter to the function addBook

$('#quu').append('<div onclick="addBook('+quote.userId+', ''+quote.book+'')">'+quote.book+'</div>')

var quote = {userId : 1, book: "The GodFather"};

$(document).ready(function(){
  
  $('#quu').append('<div onclick="addBook('+quote.userId+', ''+quote.book+'')">'+quote.book+'</div>');

});

function addBook(user_id, name) {
   console.log(name);
   console.log(user_id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quu"></div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement