Mike Mike - 10 months ago 42
Javascript Question

jQuery click event on dynamically generated elements for calendar?

The answer to the following question,

var counter = 0;
$("button").click(function() {
$("h2").append("<p class='test'>click me " + (++counter) + "</p>")

$("h2").on("click", "p.test", function(){

I have a dynamically generated calendar that when you click on an individual day, instead of opening a new web page, it swaps the calendar for the events of the day. The events are listed in a table and I want to be able to click on a row and and have it trigger a function which uses
. So each row looks like the following,

<tr id="message-7">

New page in calendar loads and creates,

<tr id="message-132">

Clicking does not trigger the function. In the example from the other question, it accesses the text of the element in order to make the element unique as opposed to giving the element a unique id # as in my situation.

Am I approaching the problem the wrong way? Could I add something like a
tag that I could reference?

Answer Source

Ideally try not to make too much meaning out of the ID. Instead use data as shown here.

So instead of

<tr id="message-7">


<tr id="1234567" data-message="7">

Then in code you can address the data as:

var messageVal = $("#1234567").data("message")

And if you need to add a generic click event then you might want to use a dummy css class assignment for all appropriate TR's:

 <tr id="1234567" data-message="7" class="messageRow">

so that you can write

$(".messageRow").on("click", function(event){
    var messageVal = $(this).data("message")

This is useful in the case where only some TR's will contain clickable content - just don't assign the class to the others.