2

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?

0

3 Answers 3

5

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.

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

1 Comment

+1. Trying to pass stringed variables into a JavaScript snippet in an event handler attribute is madness
3

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

Comments

1

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.

1 Comment

As Mike wrote, you're still missing a ).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.