Null Reference
Null Reference

Reputation: 11340

jQuery .click() doesn't fire but onclick does

I have a $each loop in jquery that adds rows into a table like this:

                $.each(result, function (index) {
                    var data = result[index];
                    cameraIcon = GetCameraIcon();
                    cameraIcon = cameraIcon.replace("$cameraId", data.CameraFQID);                       
                    var tr = "<tr><td>" + cameraIcon + "</td><td>" + icon + '</td><td>' + timestamp.format('DD/MM/YYYY HH:mm:ss') + '</td><td>' + data.DeviceLink + '</td><td>' + data.EventMessage + '</td><td>' + data.CardId + '</td></tr>';
                    $('#eventTable tr:first').after(tr);
                });

    function GetCameraIcon() {            
        return "<a href='javascript:;' class='cameraButton' id='$cameraId'><i class=\'fa fa-camera\'></i></a>";
    }

My question is: why doesn't my jquery method fire?

$(".cameraButton").click(function () {
            alert('clicked')
        });

However, when I do this:

<a href='javascript:;' onclick=\"alert('clicked')\">

It works.

My guess is some careless mistake somewhere but I can't pinpoint or figure it out

Upvotes: 0

Views: 65

Answers (3)

Ōkami X Oukarin
Ōkami X Oukarin

Reputation: 435

try this

document.getElementById("cameraId").addEventListener("click", function(){
alert("Hello World!");
});

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

If you add elements dynamically then you need to use delegated events trough on method. This should do the trick

$(document).on('click', '.cameraButton', function() {
    ...
}

Direct events won't work since elements need to already exist on your page by the time you execute the statement $(".cameraButton").click(function () {}.

Take into account that $(".cameraButton") returns an empty array in case there no element yet with class .cameraButton so click is bound to nothing.

Upvotes: 1

cssyphus
cssyphus

Reputation: 40030

It's probably event delegation. The new rows added to the table were not present when jQuery bound to its events, so you must use .on() to trap the events.

Try:

$(document).on("click", ".cameraButton", function () {
     alert('clicked');
});

Remember to add semi-colon to end of statements.

Upvotes: 2

Related Questions