I can only select a row every other time I load data.

I can only select a row every other time I load data.

joshusrejoshusre Posts: 5Questions: 2Answers: 0

Hi,

My use case is a datatable in which a user may select a row.

My table:

ts_table = $('#ts_table').DataTable({
iDisplayLength: 5,
lengthMenu: [5, 10, 20, 50, 100],
order: [[ 1, "asc" ]],
columns : [
{data:'ts_id'},
{data:'ts_name', width: '20%'},
{data:'ts_desc', width: '80%'}
],
columnDefs: [{
targets: [ 0 ],
visible: false,
searchable: false}
]
});

My event handler code is called by client generated events (document ready and when a data tables source is updated by the user)

function process_all_test_sets(msg) {
if (ts_table.data().any()) {
ts_table.rows().remove().draw();
} else {
all_test_sets_array = msg.data.split("|");
test_set_list = JSON.parse(all_test_sets_array[1]);
console.info("Adding rows to test set table.");
ts_table.rows.add(test_set_list).draw();
console.info("Adding event handler to test set table.");
$('#ts_table tbody').on('click', 'tr', function (event) {
data = ts_table.row(this).data();
console.info("Clicked " + this);
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
test_set_test_sets = [];
}
else {
$(this).removeClass('selected');
$(this).addClass('selected');
if (test_set_test_sets.length > 0) {
test_set_test_sets.shift();
}
test_set_test_sets.push(data);
}
});
}
}

My problem is that when I try to update the table, the event handler appears to be working except it doesn't add the selected class to my row. Further, this behavior happens every other time I load data. First time things work, second time they don't, third time they do and so on.

Help?

Answers

  • kthorngrenkthorngren Posts: 21,310Questions: 26Answers: 4,948

    I built a test case for you. Copied your process_all_test_sets function and event handler. Created some dummy data and splitting and JSON.parse lines.

    http://live.datatables.net/tiqaveta/1/edit

    The problem appears to be with adding the event handler each time you add data to the table. I moved the event handler out of the function and run it once. Seems to work better.

    Not sure if you code is handling the test_set_test_sets array the way you want. It only keeps track of the last row selected even though multiple may be selected.

    Kevin

This discussion has been closed.