I'm using jquery datatables. I got error of Cannot create property 'guid' on string
when I tried to retrieve the row data.
var employersTable = $('#employersTable').DataTable();
$('#add').click(function() {
addRow($('.username').val(), $('.phone').val());
});
$('body').on('click', '#employersTable tr', retrieveRow(this));
function addRow(username, phone) {
employersTable.row.add([
'<td>' + username + '</td>',
'<td>' + phone + '</td>',
]).draw();
}
function retrieveRow(e) {
alert('fire')
tr = e.target;
row = employersTable.row(tr);
detail_data = row.data();
$("#result").empty().html(detail_data[0] + " " + detail_data[1])
}
One more strange thing is my function retrieveRow fire on init, why? I put the function within a click event.
I'm using jquery datatables. I got error of Cannot create property 'guid' on string
when I tried to retrieve the row data.
http://jsfiddle.net/rqx14xep
var employersTable = $('#employersTable').DataTable();
$('#add').click(function() {
addRow($('.username').val(), $('.phone').val());
});
$('body').on('click', '#employersTable tr', retrieveRow(this));
function addRow(username, phone) {
employersTable.row.add([
'<td>' + username + '</td>',
'<td>' + phone + '</td>',
]).draw();
}
function retrieveRow(e) {
alert('fire')
tr = e.target;
row = employersTable.row(tr);
detail_data = row.data();
$("#result").empty().html(detail_data[0] + " " + detail_data[1])
}
One more strange thing is my function retrieveRow fire on init, why? I put the function within a click event.
Share Improve this question edited Dec 12, 2019 at 17:40 davidkonrad 85.5k17 gold badges209 silver badges271 bronze badges asked Jun 18, 2016 at 4:29 Alicia BrandonAlicia Brandon 5752 gold badges6 silver badges13 bronze badges 01 Answer
Reset to default 15Your main problem is this line :
$('body').on('click', '#employersTable tr', retrieveRow(this));
^^^^^^^^^^^^^^^^^
This actually executes retrieveRow()
right away. When you reference to a function variable in a on()
event handler, reference to it as it was a variable :
$('body').on('click', '#employersTable tr', retrieveRow);
You have a different problem in retrieveRow()
:
tr = e.target;
e.target
is not necessarily a <tr>
, it is most likely the <td>
you clicked on. The event handler is targeting #employersTable tr
so this
contain the reference to the <tr>
:
tr = $(this)
is the correct, more safe is
tr = $(e.target).closest('tr')
forked fiddle -> http://jsfiddle.net/nkaq816f/