Passing a parameter using the onclick function is read as a variable when it should be read as a string

Here's my problem:

I am dynamically creating a button with onclick function like this:

 $("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');


The parameters read well, but the function is not a trigger and I have this error message: "bob is not defined" when bob is the string value of param1.

It seems that bob seems to be read as a variable when it should be read as a string, but I don't understand why.

Many thanks for your help!


source to share

2 answers

This is because this line is right here:



In the end it will look like this:

'onclick="remove(foo, bar);"'


You probably want it to look like this:

'onclick="remove(\'foo\', \'bar\');"'


So change it to this:

'onclick="remove(\''+param1+'\', \''+param2+'\');"'


You can also do this:

$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
    remove(param1, param2);


Edit: I also noticed that you were missing one "from your $ () - call:" $("#test)

should $("#test")




I can offer you this

<script type="text/javascript">
    var i = 0;
    $(function () {
        $("#lnkAdder").click(function () {
            // appending new item
                $("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
                    var data = ++i;
                    alert("I'm clicked,  I'm number " + data);
<a href="javascript:;" id="lnkAdder">Add item</a>
<div id="Container"></div>


The key here is javascript closure. As you can see there is a link under the title lnkAdder

. He is responsible for adding a new item to the container. When clicked, it adds a new item to the container. On adding, you use the jQuery API and create a new element, add attributes and add an event listener. In the body of the event listener, you copy the value into an internal variable. They use it as needed.



All Articles