Reputation: 75
I am using jQuery DataTables to construct a table for which one can add and remove rows using the following scripts:
Add Row:
var row_count = 1;
$(document).ready(function() {
$('#my_table').dataTable();
} );
function fnClickAddRow() {
$('#my_table').dataTable().fnAddData( [
"<input type=\"text\" name=\"fieldA\"" + row_count + " value=\"\" />",
"<input type=\"text\" name=\"fieldB\"" + row_count + " value=\"\" />",
// ...
] );
row_count++;
}
As shown in this example.
I then add row selection and deletion with another script:
var oTable;
$(document).ready(function() {
/* Add a click handler to the rows - this could be used as a callback */
$("#my_table tbody tr").click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Add a click handler for the delete row */
$('#delete').click( function() {
var anSelected = fnGetSelected( oTable );
if ( anSelected.length !== 0 ) {
oTable.fnDeleteRow( anSelected[0] );
}
} );
/* Init the table */
oTable = $('#my_table').dataTable( );
} );
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
return oTableLocal.$('tr.row_selected');
}
The add row function (fnClickAddRow()) works fine as does the delete function on rows that are coded in HTML. However, the rows that are added to the table object are not selectable and therefore not deletable. What do I need to add to my data array to make the added rows selectable?
Upvotes: 1
Views: 2870
Reputation: 101604
To solve the class not being applied you should use .on()
(or .live()
for jQuery <1.7):
// bind to currently available (and future-added) elements
$('#my_table').on('click', 'tbody tr', function(e){
/* select code */
});
then existing <tr>
elements (and those added using fnAddRow
) will receive the click
binding.
Upvotes: 2