Skip to content Skip to sidebar Skip to footer

Passing A Parameter With Onclick Function Is Read As A Variable When It Should Be Read As A String

Here is my issue: I am creating dynamically a button with an onclick function like this: $('#test).html('

Solution 1:

That's because this string right here:

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

Will look like this in the end:

'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 could 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 be $("#test").

Solution 2:

I can suggest you this

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

The key here is the javascript closure. As you can see there a link called lnkAdder. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.

Post a Comment for "Passing A Parameter With Onclick Function Is Read As A Variable When It Should Be Read As A String"