Reputation: 1669
I'm trying to add an element before each row of table in this way:
$('tbody tr').each (function(){
var htm =$(this).html();
var tdm = "<td><button>Add</button></td>" ;
$(this).html(tdm+htm);
});
but when I add an element with jquery first it appears and then it quickly disappears. Probably datatables has a mechanism to remove external element injections. A similar question is here but doesn't work. Any help appreciated.
UPDATE Here is the datatables initialization code
$(document).ready(function() {
var table = $('#example').dataTable( {
"ajax": "?r=group/subscribe",
"columns": [
{ "data": "id" },
{ "data": "uid" },
{ "data": "first_name" }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ],
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select ><option value=""></option></select>')
.appendTo( $(column.header()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
UPDATE:
Answered by @Bala Sakthis, now the buttons appear but not before the rows, rather a new row is created for every button before the table. This information might be helpful!
Upvotes: 2
Views: 2738
Reputation: 704
Please refer the below code for adding a Button
(in all the rows) in one of the Columns:
{
"data": "Status",
"render": function (data, type, row, meta) {
return $('<button>')
.attr('class', 'btn btn-danger')
.text('Add')
.wrap('<div></div>')
.parent()
.html();
}
}
The Logic for Button Click Event can be written here:
$(document).ready(function () {
$('#example tbody').on('click', 'button', function () {
// Add Logic for Button Click Event
});
});
And check the below link for adding buttons in the Table HEADER
.
http://www.datatables.net/forums/discussion/3914/adding-buttons-to-header-or-footer
Please check the JSFiddle for the updated code.
Upvotes: 4
Reputation: 5699
So you want to add a cell that wasn't there in the first instance?
"columns": [
{
"title": "Button",
"render": function (data, type, row, meta) {
return $('<button></button>',{
'class', 'btn btn-danger',
'text': 'Add'
}).prop("outerHTML");
}
},{
"data": "id"
},{
"data": "uid"
},{
"data": "first_name"
}
]
If you replace your columns
array with this and get rid of the columnDefs
and initComplete
does this work for you?
Upvotes: 1