row select not working when data loaded from a json file

row select not working when data loaded from a json file

bigsipperbigsipper Posts: 31Questions: 2Answers: 0
edited January 2014 in DataTables 1.9
http://jsfiddle.net/bigsipper/bVyCC/1/

I don't understand why row select - specifically the jquery '$('#example tbody tr').click( function() {...' - does not
work when I use
[code]
oTable = $('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": 'viewdata.json'
});
/* Add/remove class to a row when clicked on */
oClick = $('#example tbody tr').click( function() {
c = $(this).toggleClass('row_selected');
} );


[/code]

I'll put the contents of vewdata.json at the end of this post... this http://jsfiddle.net/bigsipper/bVyCC/1/ jsfiddle shows what I am trying to do, but it doesn't run.

I want to (simply) build a datatable (from a json file) and have multi row selection and highlighting. My example will display
the table and show the filter and sort buttons. But row selection just doesn't happen. If I use firebug to 'watch' the html, the
class of the 'tr' never toggles the 'row_selected' class. Its as if the on.click never fires. If I do the same thing,
but build the table in html it works fine. If I use json... ah, no bueno.

I must be lacking some information about the jquery selector. Does it CHANGE just when DataTables loads from 'sAjaxSource'????
Please send a clue....

-Bigsipper


[code]
[1178] ; cat viewdata.json

{
"aaData": [
[
"Trident",
"Internet Explorer 4.0",
"Win 95+",
"4",
"X"
],
[
"Trident",
"Internet Explorer 5.0",
"Win 95+",
"5",
"C"
],
[
"Trident",
"Internet Explorer 5.5",
"Win 95+",
"5.5",
"A"
],
[
"Trident",
"Internet Explorer 6",
"Win 98+",
"6",
"A"
]
]
}

[/code]

Replies

  • bigsipperbigsipper Posts: 31Questions: 2Answers: 0
    Datatables debug: http://debug.datatables.net/onaqap
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Its not running because you are using a static event handler and the rows haven't been ovulated by the time the event adder runs. So it doesn't find any rows and thus doesn't add any events.

    Use a delegated event handler:

    [code]
    $('#example tbody').on( 'click', 'td', function (e) {...
    [/code]

    See also the top FAQ: http://datatables.net/faqs .

    Allan
  • bigsipperbigsipper Posts: 31Questions: 2Answers: 0
    edited January 2014
    ah... your clue was very helpful.

    This did the trick:
    [code]
    $("#example").on( 'click', 'tr', function(){ $( this ).toggleClass('row_selected');} );
    [/code]
This discussion has been closed.