alfajango / jquery-dynatable

A more-fun, semantic, alternative to datatables
http://www.dynatable.com
Other
2.77k stars 361 forks source link

click event for every row #130

Closed Lioxen closed 10 years ago

Lioxen commented 10 years ago

How do I set a click event for every row? Thanks in advance.

mjmadelo-ih commented 10 years ago

Hi Lioxen! Have you figured out how to do this? I actually have the same concern. Thank you.

JangoSteve commented 10 years ago

Use a delegated click handler like this:

$('#my-table').dynatable().on('click', 'tr', function() {
  // do stuff here
});
mjmadelo-ih commented 10 years ago

Thank you @JangoSteve ! I didn't realize that the solution is just the same with html created tables. Your comment helped me a lot. It worked as how I hoped it would.

Lioxen commented 10 years ago

@mjmadelo I'm glad the solution is working. I'm using a slightly different solution, because I also like to drag my table cells (this part I omitted in my example) and my table has a footer also with tr tags.

$('#my-table').dynatable().bind("dynatable:afterUpdate",  function(e, rows) {
   $(e.target).children("tbody").children().each(function(i){
       $(this).click(function(){
            //do your stuff here
        });
    });
});
JangoSteve commented 10 years ago

Just to offer once more solution (for the sake of completeness), you could also change the default row rendering function with something like this:

$('#my-table').dynatable({
  writers: {
      _rowWriter: myRowWriter
  }
});

function myRowWriter(rowIndex, record, columns, cellWriter) {
  var tr = '';

  // grab the record's attribute for each column
  for (var i = 0, len = columns.length; i < len; i++) {
    tr += cellWriter(columns[i], record);
  }

  return '<tr class="my-row">' + tr + '</tr>';
};

And then bind to those rows indirectly:

$(document).on('click', '.my-row', function() {
  // do stuff
});
drouillard commented 10 years ago

Closing as it looks like solution has been found