ashok19r91d
ashok19r91d

Reputation: 494

DataTable select plugin and jquery event handler issue

I have read several articles and jQuery API documentation and understand there is no difference between click() and on('click') other than event delegate.

And I'm using Datatables and its select plugin in my page; My Html Tag and script is something identical to following code.

<div class='panel'>
    <table class='data-table'>
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
        </thead>
        <tbody>
            <tr data-id='1'>
                <td>Row 1, 1</td>
                <td>Row 1, 2</td>
            </td>
            <tr data-id='2'>
                <td>Row 2, 1</td>
                <td>Row 2, 2</td>
            </td>
            <tr data-id='3'>
                <td>Row 3, 1</td>
                <td>Row 3, 2</td>
            </td>

        </tbody>
    </table>
</div>

<script>
    $('table tbody tr').click(function(){
        console.log("Click(): " + $('table tr.selected').data('id'));
    });
    $('table').on('click', 'tbody tr', function() {
        console.log("On(Click()): " + $('table tr.selected').data('id'));
    });
</script>

when click() and on('click') are same I have to get same console results, but what I got is after selecting first row (data-id=1)

On(Click()): undefined
Click(): 1

then on clicking second row from first

On(Click()): 1
Click(): 2

that is I see that on('click()') runs before data-table's selection routine and click() runs after same. what will be the possible fix to apply so that both click() and on(click()) execute after datatables selection routine.

As the dataset in my table is huge in number I need to apply delegation i.e., on(click()).

Update

using this in events will give access to get selected row, but clicking same row second time in data-table will remove selection, so the result should be undefined for both functions.

Upvotes: 0

Views: 615

Answers (1)

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

In your jquery selector, use this keyword instead:

$('table tbody tr').click(function(){
    if($(this).hasClass( "selected" ) == true) {
        console.log("Click(): " + $(this).data('id'));
    }
});
$('.data-table').on('click', 'tbody tr', function() {
    if (!$(this).hasClass('selected'))
        console.log("On(Click()): " + $(this).data('id'));
    else
        console.log('nothing selected');
});

Upvotes: 1

Related Questions