DLiKS
DLiKS

Reputation: 1596

Uncaught SyntaxError: Unexpected token }

I have a piece of jQuery code which appends an input button to the body and then assigns an onclick function to it. The function that is meant to be called has been defined elsewhere and takes two arguments which are variables that have been defined just before.

This is the code I'm currently using:

$("body").append("<input type='submit' value='foo' onclick='foo(\'" + argument1 + "\',\'" + argument2 + "\'/>");

However, when I try to click on the button, I get an error (in Chrome) saying: Uncaught SyntaxError: Unexpected token }.

Can anyone help me?

Upvotes: 2

Views: 5995

Answers (3)

kennytm
kennytm

Reputation: 523214

Suppose argument1 == '1' and argument2 == '2', your .append will give

<input type='submit' value='foo' onclick='foo('1','1'/>

which is obviously not valid HTML. To fix it you should use

.append("<input ... onclick='foo(\"" + argument1 + "\",\"" + argument2 + "\")'/>")

But this is not the right way to use jQuery. See @SLaks's answer for better code.

Upvotes: 1

SLaks
SLaks

Reputation: 887305

You should assign the click handler using jQuery:

var input = $('<input type="submit" value="foo" />')
    .click(function() { foo(argument1, argument2); })
    .appendTo(document.body);

Note that this will capture the argument variables by reference.

Upvotes: 5

Mike Robinson
Mike Robinson

Reputation: 25159

You haven't closed the foo() function in the onclick

Upvotes: 3

Related Questions