Reputation: 873
I am adding a row to the table using the following function:
function loadTable()
{
var index, html, tbody;
//clear the table
for (index = 0; index < content.length; index++)
{
var tbody = document.getElementById("tablei").getElementsByTagName('tbody')[0];
var row = document.createElement("TR");
row.setAttribute("id", index);
row.setAttribute("class", "selectableRow editableDiv");
var td1 = document.createElement("TD");
td1.innerHTML = content[index].Author;
var td2 = document.createElement("TD");
td2.innerHTML = content[index].AuthorType;
var td3 = document.createElement("TD");
td3.innerHTML = content[index].CosignStatus;
var td4 = document.createElement("TD");
td4.innerHTML = content[index].FileTime;
var td5 = document.createElement("TD");
td5.innerHTML = content[index].NoteTime;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
tbody.appendChild(row);
}
}
I added a jquery function to catch the clicking event on the row.
$('.selectableRow').click(function (event)
{
var id = $(this).attr('id');
var item = content[parseInt(id)];
alert(id);
}
But no alert shows up when the row is clicked.
But twhen I add the same code directly in html, the alert is called.
Upvotes: 0
Views: 51
Reputation: 3464
Your approach not work because you are adding a listener only to the existing tr
. You need to add the listener after of append the new tr
you can wrap the click event on a function to call just after append the element.
Just remember to unbind the event when you add the new one
$(element).unbind('click', function(){});
$(element).bind('click', function(){});
Here is a fiddle with a example
https://jsfiddle.net/mhr9coLs/1/
Upvotes: 0
Reputation: 1140
That's because you are adding a handler to things that don't yet exist.
Try wrapping your click handler inside a change()
function:
$(document).change(function(){
$('.selectableRow').click(function (event){
var id = $(this).attr('id');
var item = content[parseInt(id)];
alert(id);
})
});
Even better, you could do:
$(document).on('click', '.selectableRow', function() {
var id = $(this).attr('id');
var item = content[parseInt(id)];
alert(id);
});
From JQuery on()
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Upvotes: 4