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?
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?
Share Improve this question asked Mar 12, 2016 at 10:54 Kadzhaev MaratKadzhaev Marat 1,3172 gold badges19 silver badges33 bronze badges2 Answers
Reset to default 4You 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quu"></div>
You don't append a function. You need to bind the function, you can do it using JQuery bind:
$( "#foo" ).bind({
click: function() {
// Do something on click
},
mouseenter: function() {
// Do something on mouseenter
}
});