Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row data failed, error of Cannot create property 'guid' on string

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.

like image 616
Alicia Brandon Avatar asked Jun 18 '16 04:06

Alicia Brandon


1 Answers

Your 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/

like image 115
davidkonrad Avatar answered Nov 04 '22 19:11

davidkonrad