Datatables select row programmatically without triggering select event - javascript

In Datatable's Select plugin, there is a way to programmatically select a row:
https://datatables.net/reference/api/row().select()
But this will also trigger the row's select event, which is not ideal in my context as it will get into an infinite loop...
Is there a way of doing this without having to use some control variable?
The bit in their API for the select function is as follows :
apiRegisterPlural( 'rows().select()', 'row().select()', function ( select ) {
var api = this;
if ( select === false ) {
return this.deselect();
}
this.iterator( 'row', function ( ctx, idx ) {
clear( ctx );
ctx.aoData[ idx ]._select_selected = true;
$( ctx.aoData[ idx ].nTr ).addClass( ctx._select.className );
} );
this.iterator( 'table', function ( ctx, i ) {
eventTrigger( api, 'select', [ 'row', api[i] ], true );
} );
return this;
} );
It seems I just need to figure out the ctx.aoData[ idx ]._select_selected = true; part, is ctx the row object? I'm clueless.

I know this question is very old, but for those coming here later on might like an answer.
Datatables has a select event and a user-select event.
Just use the user-select event where applicable and leave the select event for all other purposes.
https://datatables.net/reference/event/user-select
For example,
var table = $('#example').DataTable( {
select: true
} );
table
.on( 'user-select', function ( e, dt, type, cell, originalEvent ) {
if ( originalEvent.target.nodeName.toLowerCase() === 'img' ) {
e.preventDefault();
}
} );
Update : Just to add an additional choice since the user-select event does fire even on a deselect. One way to avoid some issues I think many people have is when the table is initialized they programmatically select items. You can avoid this trigger by simply enabling your select and deselect events only after the table has been initialized.
Datatables has an initComplete event. So do it like so. Where table is a variable to your datatable reference.
initComplete: function(settings, json) {
table.on('select', function( e, dt, type, indexes ) {
});
}

Related

Angular databinding on datable row selection

I am using Datatables to show data. When I click on a row, I want to work on the data and then do databinding to show these data. Here is the code I have for the datatable event :
table.on( 'select', function ( e, dt, type, indexes ) {
$scope.siege = {
economique: 30,
affaire: 30,
premiere: 30
};
if ( type === 'row' ) {
var avion = table.rows( indexes ).data()[0];
$scope.getConfiguration(avion);
// do something with the ID of the selected items
}
} );
As you can see, for the example, I want to bind data to $scope.siege but it doesn't work and there is nothing prompt in the console.
However, if I put :
$scope.siege = {
economique: 30,
affaire: 30,
premiere: 30
};
Somewhere else in the controller it works.
Thank you for your help.
Try to put a $scope.$apply .. cause it let angular knows that you need to refresh your $scope (if you're outside angular events) .. something like:
table.on( 'select', function ( e, dt, type, indexes ) {
$scope.siege = {
economique: 30,
affaire: 30,
premiere: 30
};
if ( type === 'row' ) {
$cope.$apply(function(){
var avion = table.rows( indexes ).data()[0];
$scope.getConfiguration(avion);
// do something with the ID of the selected items
})
}
} );

Jquery datatable click event is not firing for second time

Jquery Click event is firing for first time but on second time it is not triggering.
Datatable:
var tableAttendance = $('#tableAttendance').dataTable ({
"bDestroy" : true,
"bAutoWidth" : false,
"bServerSide" : true,
"bDeferRender" : true,
"sServerMethod" : "POST",
"sAjaxSource" : pageUrl (),
"sAjaxDataProp" : "aaData",
"aaSorting" : [[2, 'desc']],
"fnCreatedRow": function( nRow, aData, iDataIndex ) {
$(nRow).attr({
"data-toggle":"context",
"data-target":"#attendance-context-menu"
});
},
"aoColumns" : [
{
"mData" : function (row, type, set) {
return '<div>'+ row['Employee_Name'] +'</div>';
}
}]
});
Jquery Event :
$(document).on('click contextmenu', '#tableAttendance tbody tr', function (e) {
console.log("Event Triggered");
var selectRow = $(this);
if (!selectRow.hasClass('row_selected'))
{
selectRow.addClass('row_selected');
}
else
{
//Other than right click. Because i use multi-select option
if( e.button !== 2 )
selectRow.removeClass('row_selected');
}
});
Working for different row select event. But when i right click(context menu) same row more than once, the event is not triggring
Just tested and your code works for me.
Could you please try to modify your click handler as follows:
$(document).on('click contextmenu', '#dummy tbody tr', function () {
var d = new Date();
console.log("Event Triggered" + d.getMilliseconds());
});
If you are debugging with firebug it could well be that you overlooked the number in front of your logged text.
Messages with the exact same content logged multiple times result in the number being incremented.
Adding milliseconds to the output will slightly modify the message and result in a new line of output.
EDIT:
A right click will result in the value e.button = 2.
This value is checked in your handler if( e.button !== 2 ) and does not execute selectRow.removeClass('row_selected'); because the result of the check is false.
Completely removing the check for e.button would get your right-click to select and deselect the rows.

Angularjs jQuery datatables add processing event

I use the Angular datatables module. https://github.com/l-lin/angular-datatables
I try add the processing.dt event, but it does not work.
This is the original code from the base api
https://datatables.net/reference/event/processing
$('#example')
.on( 'processing.dt', function ( e, settings, processing ) {
$('#processingIndicator').css( 'display', processing ? 'block' : 'none' );
} )
.dataTable();
And this is my unworked code
.withOption('processing.dt', function( e, settings, processing){
console.log(processing);
$scope.loading = processing;
}) .withOption('initComplete', function(){
$scope.loading = false;
})
There is no difference in using the dataTables events when dealing with angular datatables. If you have a table
<table datatable dt-options="dtOptions" dt-columns="dtColumns" id="example">
then this works [ http://plnkr.co/edit/hBDjR9ytD0hK6YgwrgMd?p=preview ]
$('#example').on('processing.dt', function() {
console.log('processiong.dt');
})
and this works [ http://plnkr.co/edit/zKYyrneXl2YudNTXZkXv?p=preview ]
angular.element('#example').on('processing.dt', function() {
console.log('processiong.dt');
})
If you use a dtInstance you can even attach event listeners to that too (here waiting for dtInstance to be initialised, then attaching a order.dt handler [ http://plnkr.co/edit/DJa1xwzxArrWhplDY278?p=preview ]) :
$scope.dtInstance = {}
$scope.$watch('dtInstance', function() {
if ($scope.dtInstance.DataTable) {
$scope.dtInstance.DataTable.on('order.dt', function() {
console.log('order.dt')
})
}
})
Just to demonstrate that there is no particular "angular datatables" way of handling events, it is basically the exact same - you just have a few more options since you also have the angular.element() way and can work on the special dtInstance object.

DataTables pre-select filter option to show specific data

I have searched high and low on how to set the default option of a dataTable column filter but I cannot find out how to do it. I am still a novice with DT's so I figured I would hit SO first and then tear into hours of documentation if nothing presents itself.
In any case, I have a function set up to to instantiate a new DT. It then adds a column filter to the "username" column in my table. The data all shows fine in the table. Success!!
In my column filter I have several usernames that appear as options. My question: how to I preselect one of the options and only make that users data show up in the table.
Scenario: In my users column I have the value of "Peter Pan". In my users column filter I have the option "Peter Pan". I am passing the value of "Peter Pan" into the page. How to I only show the value of Peter Pan in the table?
$(document).ready(function() {
$('#userListTable').DataTable( {
initComplete: function () {
var api = this.api();
api.columns().indexes().flatten().each( function ( i ) {
var column = api.column( 2 );
var select = $('<select><option value=""></option></select>')
.appendTo(
$(column.header()).empty()
).on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex( $(this).val() );
column.search( val ? '^'+val+'$' : '', true, false ).draw();
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
select.val("Peter Pan");
select.trigger('change');
} );
}
} );
});
Thanks!

jquery autocomplete with different sources

I hope you can help me. I'm looking for a possibility to make my jquery autocompleter use a different source whether the first input is a digit or a letter (on the fly). I tried days and could not make it working.
Thats the autocomplete code:
$(function() {
$("#ac1").autocomplete(
'search.php', //or blub.php
{onItemSelect: function(item) {
var text = 'test';
$("#num1").val(item.data);
var selector = $("#num1").val();
var additionalradius = selector.substring(0,3);
var zip = selector.substring(6);
$("#num1").val(additionalradius);
$("#3rd").val(zip);
alert (additionalradius);
}},
{selectFirst: true}
);
});
So I need something like "if first key in field #ac1 is a number, then use search.php. Else use blub.php" in that code shown. Any idea? Thank you for you help.
To set the source option in search event ( that is triggered before a search is performed ) is one way to do it.
$("#ac1").autocomplete({
source: 'search.php',
search: function( event, ui ) {
if ( isNaN( parseInt( $(this).val().charAt(0) ) ) )
$(this).autocomplete( 'option', 'source', 'blub.php' );
else
$(this).autocomplete( 'option', 'source', 'search.php' );
}
});
EDIT:
$("#ac1").autocomplete({
source: 'search.php',
search: function( event, ui ) { /* code from search function here */ },
select: function( event, ui ) { /* code for item select here */ }
/* additional options */
});

Categories