J. Ano J. Ano - 5 months ago 13
HTML Question

How to call an div's attributes value using a function if there are many div's with the same function?

I have the following code:

function openCanviewer() {
var cid = $(this).data('cid');
alert(cid);
}


And the HTML:

<div onclick="openCanviewer();" data-cid="ID OF CAN FROM DATABASE"></div>


My problem is that when I click the element with the onclick function, which I have many of because they get inserted from the database, the alert is just showing "undefined" instead of the contents of the data-cid attribute. Does someone have any idea what I have done wrong, or what I am missing here?

Answer Source

In general you shouldn't use inline events like onclick="openCanviewer();", you should always keep js, css and html separate.

For your problem you could use delegate event listening:

function openCanviewer() {
  var cid = $(this).data('cid');
  alert(cid);
}

$(document).on('click', '[data-cid]', openCanviewer)