3

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?

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

yes, it help me, but now I get another error: Unexpected token ILLEGAL, why is so?
I have added a code snippet which is working properly, I really cant guess the ILLEGAL error unless you show us the full code
0

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
       }
    });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.