I have a basic HTML table that gets loaded. The structure differs based on and uploaded CSV file’s content. The table columns need to be drag-able (for which I use a plugin called Dragtable). I then have methods to add rows and columns. The add column method looks like this:
function addCol(tblId) {
var tblHeadObj = document.getElementById(tblId).tHead;
for (var h=0; h < tblHeadObj.rows.length; h++) {
var newTH = document.createElement('th');
tblHeadObj.rows[h].appendChild(newTH);
colCount = (tblHeadObj.rows[h].cells.length);
newTH.innerHTML = 'Col ' + colCount;
}
var tblBodyObj = document.getElementById(tblId).tBodies[0];
for (var i=0; i<tblBodyObj.rows.length; i++) {
var newCell = tblBodyObj.rows[i].insertCell(-1);
newCell.innerHTML = "*null*";
}
}
The problem is that when I add a new column, I can no longer drag that column to place it in a different spot. I also have an onclick handler for table headings which allow the user to delete a column when he clicks on the th element. This also does not work on newly added columns. Basically, all event listeners are not added on new columns.
I have tried hiding and showing the table and the page, which does not work. I think I need a way for the table to be refreshed, but cannot find something that works.
Something like this:
var table = document.getElementById("grid");
table.refresh ();
Is there a way to accomplish this? Or is there something wrong with the way I add columns which could be the reason why the event listeners are not attached?
EDIT
The delete column method is below: (Edited with proper event delegation) This fixed the problem for the delete column method. I am still unable to drag and sort new columns though
$("table").delegate("th:not(:first)", "click", function() {
var index = this.cellIndex;
$(this).closest('table').find('tr').each(function() {
this.removeChild(this.cells[ index ]);
});
}
Regarding the Dragtable column sorting, I just add the draggable class to my table. I’m not sure how the event listener looks:
<table id = "grid" class="draggable"></table>
You should use event delegation for this. What you should do is add an event listener to the table itself, which checks the
.targetproperty of the event object to see if the event is targeted at a heading and takes the appropriate action.Aside from the event delegation approach, another easy fix you could make is to simply attach the handler when you add a new row:
As j08691 has pointed out, you may have tagged jQuery mistakenly, so I am not adding any jQuery code for now