Single check box selection with jquery datatable - javascript

In jquery datatable, single check box should be selected.
This link is working fine.
But above link is using jquery.dataTables 1.10.16 version. And I am using jquery.dataTables 1.9.4.
Can the same functionality as listed in example given above be possible with jquery.dataTables 1.9.4 instead of jquery.dataTables 1.10.16?

In the same page which you give the link, there are many explanation about to using "single check" oparetion.
At the end of the listed attachment, you can see the referanced .js file is
https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js
In your page, you should add this file referance after dataTable.js.
I think, the version of jquery is not important. The important file is "dataTables.select.js"!
Secondly, you must update your dataTable maker codes like the sample below;
$(document).ready(function() {
$('#example').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child' // this line is the most importan!
},
order: [[ 1, 'asc' ]]
} );
} );
UPDATES :
Why dont you try to write your own selector function?
for example;
$(document).ready(function() {
$('#example').DataTable( {
/// put your options here...
} );
$('#example').find("tr").click(function(){ CheckTheRow(this); });
} );
function CheckTheRow(tr){
if($(tr).find("td:first").hasClass("selected")) return;
// get the pagination row count
var activePaginationSelected = $("#example_length").find("select").val();
// show all rows
$("#example_length").find("select").val(-1).trigger("change");
// remove the previous selection mark
$("#example").find("tr").each(function(i,a){
$(a).find("td:first").removeClass("selected");
$(a).find("td:first").html("");
});
// mark the picked row
$(tr).find("td:first").addClass("selected");
$(tr).find("td:first").html("<i class='fa fa-check'></i>");
// re turn the pagination to first stuation
$("#example_length").find("select")
.val(activePaginationSelected).trigger("change");
}

Unfortunately, legacy data table does not support or have that select extension.
Workaround:
Create checkbox element inside 'mRender' callback.
Bind action to the checkbox. (This can be done inside the fnRowCallback or outside as in my example in below fiddle
https://jsfiddle.net/Rohith_KP/dwcatt9n/1/
$(document).ready(function() {
var userData = [
["1", "Email", "Full Name", "Member"],
["2", "Email", "Full Name", "Member"]
];
var table = $('#example').DataTable({
'data': userData,
'columnDefs': [{
'targets': 0,
'className': 'dt-body-center',
'mRender': function(data, type, full, meta) {
return '<input type="checkbox" value="' + $('<div/>').text(data).html() + '">';
}
}],
'order': [1, 'asc']
});
$('#example tr').click(function() {
if ($(this).hasClass('row_selected'))
$(this).removeClass('row_selected');
else
$(this).addClass('row_selected');
});
});
Also, I suggest you to upgrade your datatable version. Then you can use that select extension.

Can the same functionality as listed in example given above be possible with jquery.dataTables 1.9.4 instead of jquery.dataTables 1.10.16?
Yes.
But, not using the Select Extension since it requires at least version 1.10.7.
For 1.9.4, a possible solution would be:
$(document).ready(function() {
$('#example').find("td input[type='checkbox']").click(function() {
selectRow(this);
});
var table = $('#example').DataTable();
function selectRow(clickedCheckBox) {
var currentPage = table.fnPagingInfo().iPage;
// Being unchecked
if (!$(clickedCheckBox).is(':checked')) {
$(clickedCheckBox).removeAttr('checked');
getRow(clickedCheckBox).removeClass('selected');
return;
}
var selectEntries = $("#example_length").find("select");
var showEntriesCount = selectEntries.val();
var totalRows = table.fnGetData().length;
// If show entries != totalRows append total rows opiton that can be selected
if (totalRows != showEntriesCount)
selectEntries.append($('<option>', {
value: totalRows,
text: totalRows
}));
// Display all rows
selectEntries.val(totalRows).trigger("change");
// Removes all checked attribute from all the rows
$("#example").find("td input[type='checkbox']").each(function(value, key) {
getRow(key).removeClass('selected');
$(key).removeAttr('checked');
});
// Check the clicked checkBox
$(clickedCheckBox).prop('checked', true);
getRow(clickedCheckBox).addClass('selected');
// Re set the show entries count
selectEntries.val(showEntriesCount).trigger("change");
// If added, Remove the additional option added to Show Entries
if (totalRows != showEntriesCount)
selectEntries.find("[value='" + totalRows + "']").remove();
// Go to the page on which the checkbox was clicked
table.fnPageChange(currentPage);
}
function getRow(element) {
return $(element).parent().parent();
}
});
The above will require fnPagingInfo to take the user back to initial page. I haven't tested the solution on large dataset, tested it on a table with 150 rows, but should work fine on larger datasets too.
JSFiddle

Have you tried below code and I checked and it is working fine, you need to update styles and scripts:
You havr to update the latest styles and scripts to achieve latest functionality.
Single check box selection with jquery datatable

Related

How to display Jquery datatable information in print view?

I want to include datatable information in the print view.
Example I want to show this information in the print view: Showing 1 to 9 of 9 entries
Any help will be appreciated.
I've just played with the print option myself to see if I can wing it; including the footer didn't do much but add the same footer to the bottom of the table in print view; however; if you use the custom message you may be able to produce a good result; you can for example set a custom message showing total entries above or below your printed document.
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
messageBottom: function () {
var oTable = $('#example').DataTable();
var info = oTable.page.info();
var count = info.recordsTotal;
return 'Showing total entries of ' + count;
}
}
]
} );
});
You can play with either messageBottom or messageTop; or display both with two different messages.

Custom plugin with DOM manipulation CKEditor 4.x

I am developing one custom plugin for the CKEditor 4.7 which do a simple think take in case user select some stuff it will put it in a div with specific class, else it will put a div with same class just with text like 'Add content here'
I try to use some functions according to CKEditor docs but have something really wrong.
here is the code for the plugin folder name=> customdiv, file=> plugin.js
CKEDITOR.plugins.add('customdiv', {
icons: 'smile',
init: function (editor) {
editor.addCommand( 'customdiv',{
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
}else{
selection='<div class="desktop">Add your text here </div>';
}
return {
selection
};
}
});
editor.ui.addButton( 'Customdiv',
{
label : 'Custom div',
command : 'customdiv',
toolbar: 'customdiv',
icon : this.path + 'smile.png'
});
if (editor.contextMenu) {
editor.addMenuGroup('divGroup');
editor.addMenuItem('customdiv', {
label: 'Customdiv',
icon: this.path + 'icons/smile.png',
command: 'customdiv',
group: 'divGroup'
});
editor.contextMenu.addListener(function (element) {
if (element.getAscendant('customdiv', true)) {
}
});
}
}
});
According to some docs it have to return the result good.
Also this is how I call them in my config.js file
CKEDITOR.editorConfig = function (config) {
config.extraPlugins = 'templates,customdiv';
config.allowedContent = true;
config.toolbar = 'Custom';
config.toolbar_Custom = [
{ name: 'divGroup', items: [ 'Customdiv' ] },
{name: 'document', items: ['Source', '-', 'Save', 'Preview', '-', 'Newplugin']},
/* MOre plugins options here */
];
};
Note: the official forum was close and moved here :(
UPDATE
I have change the function like this
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}else{
selection='<div class="desktop">Add your text here </div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}
}
This makes it work for the else part, but still can't get the selected one.
UPDATE 2
After change of the if I can get data if is selected, but when I do insert selected between <div> I face a problem.
var selection = editor.getSelection();
give like result an object, and I funded out a more complex function and I get collected data like this
var selection = editor.getSelection().getNative();
alert(selection);
from this in alert I see the proper selection and not just object,but when I insert it like
CKEDITOR.instances.editor1.insertHtml('<div class="desktop">' + selection + '</div>');
it just put all selected in one line and not adding the div, new div for else case working with this syntax.
UPDATE 3
The problem now is this function
CKEDITOR.instances.editor1.insertHtml('<div>' + selection + '<div>');
it delete all existing HTML tags even if I add just selection without <div> I am not sure if this is because of the way I insert data or way I collect data, just in alert when I collect data I see correct space like in the editor.
user select some stuff it will put it in a div with specific class
If you want to check if selection is not empty, please instead of selection.length>0 try using !selection().getRanges()[0].collapsed.
If you need something more advanced you could also try using
!!CKEDITOR.instances.editor1.getSelection().getSelectedText() to see if any text was selected and !!CKEDITOR.instances.editor1.getSelection().getSelectedElement() to see if any element like e.g. image, tabl,e widget or anchor was selected.
EDIT:
If you need selected HTML please use CKEDITOR.instances.editor1.getSelectedHtml().getHtml();
Please also have a look at CKEditor documentation:
https://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-getSelectedHtml
https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_documentFragment.html#method-getHtml
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedText
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedElement

Jquery - Add hyperlink to datatables

Using the DataTable plugin I am able to generate a table just fine but I want a custom hyperlink on one of the columns that links to another page but taking information from the rest of the row...for example in row 1 I want a hyperlink: http://url/?data['imdata'][i]['faultInst']["attributes"]["code"] or something like that. I've seen a lot of complicated examples from other forms but couldn't get it to work. Looking for the simplest solution as this is a side project and I need it to be completed.
$(document).ready(function(){
$.getJSON('/static/faults.json', function (data) {
var test = $('#table5').DataTable({
});
var tr;
for (var i = 0; i < data["totalCount"]; i++) {
test.row.add([
data['imdata'][i]['faultInst']["attributes"]["code"],
data['imdata'][i]['faultInst']["attributes"]["cause"],
data['imdata'][i]['faultInst']["attributes"]["descr"],
data['imdata'][i]['faultInst']["attributes"]["created"],
data['imdata'][i]['faultInst']["attributes"]["changeSet"],
data['imdata'][i]['faultInst']["attributes"]["childAction"],
data['imdata'][i]['faultInst']["attributes"]["dn"],
data['imdata'][i]['faultInst']["attributes"]["domain"],
data['imdata'][i]['faultInst']["attributes"]["highestSeverity"],
data['imdata'][i]['faultInst']["attributes"]["lastTransition"],
data['imdata'][i]['faultInst']["attributes"]["lc"],
data['imdata'][i]['faultInst']["attributes"]["occur"],
data['imdata'][i]['faultInst']["attributes"]["origSeverity"],
data['imdata'][i]['faultInst']["attributes"]["prevSeverity"],
data['imdata'][i]['faultInst']["attributes"]["rule"],
"test",
//data['imdata'][i]['faultInst']["attributes"]["Severity"],
data['imdata'][i]['faultInst']["attributes"]["subject"],
data['imdata'][i]['faultInst']["attributes"]["type"],
//data['imdata'][i]['faultInst']['attributes']["ack"]
"test",
"test"
])
}
test.draw();
});
});
When you have a setup like this, just avoid to define data, by that you get the proper value you can turn into a link. dataTables know which data it should pass to the render function by the targets value. Example :
var table = $('#example').DataTable({
columnDefs : [
{ targets : [0],
render : function(data) {
return '<a href="'+data+'" target_blank>'+data+'</a>'
}
}
]
})
table.row.add(['https://example.com', 'david', 'programmer']).draw()
demo -> http://jsfiddle.net/47k7nhkb/

jQuery datatables - Index Column print/download issue

I am using a jquery datatables api index column. I've managed to make the table work by following the documentation shown on the page.
I also used the Buttons plugin to print the table, but in the "index" -- or in my case I named it "Bil" -- column, the numbers are not printed out.
The same problem occurs when I want to view the data after downloading the table in Excel and PDF.
The output when I wanted to print the table:
I don't know if it is a bug or not since I can't find the issue raised else where. I suspect the index value was only loaded to the page but is not inserted into the table. Is there a workaround to maybe use javascript to insert the value inside the table's ?
Here is the datatable's javascript that is responsible for the indexing:
//Datatable
var t = $('#tablePelajarLama').DataTable({
dom: 'lBfrtip',
buttons: [
'copy', 'excel', 'pdf', 'print'
],
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
});
//index counter
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
On a side note, I use PHP to load the data into the table if it in any way affects the process. Thanks.
SOLUTION
You need to use cell().invalidate() API method to tell DataTables to re-read the information from the DOM for the cell holding the index.
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i + 1;
t.cell(cell).invalidate('dom');
} );
} ).draw();
DEMO
See this jsFiddle for code and demonstration.

jquery datatable add class to row

I have a datatable which when I click on a row, it highlights the row. I want to save the row index and use it to re-highlight that row when the page is reloaded.
var table = $('#example').DataTable( {
"ajax": "DataQueries/FetchOpenJobs.asp",
stateSave: true,
"aLengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
"iDisplayLength": 25,
"order": [[ 0, "desc" ]],
columnDefs: [
{"visible": false, "targets": [2,3]},
{"type": 'date-uk', "targets": [1,9,10] },
{"type": 'title-string', "targets": [11] }
],
} );
I am able to get the row index using the below:
var selectedRowIndex = table.row(this).index();
However, I am unsure as to how to re-highlight using the row index.
I think this question deserves a more thorough example.
I would save the selected id('s) in the localStorage as an stringified array. When the page is (re)loaded then retrieve the array and if it contains any stored indexes, highlight the corresponding rows. Below a code example in explanatory order :
Sample code of highlightning rows when they are clicked :
$('#example').on('click', 'tr', function() {
$(this).toggleClass('highlight');
processSelected(table.row(this).index(), $(this).hasClass('highlight'));
});
Basic code for maintaining an array of highlighted row indexes in the localStorage :
function processSelected(id, selected) {
if (selected) {
selectedRows.push(id);
} else {
selectedRows.splice(selectedRows.indexOf(id), 1);
}
localStorage.setItem('selectedRows', JSON.stringify(selectedRows));
}
When the page is loaded, retrieve the array from localStorage :
var selectedRows = JSON.parse(localStorage.getItem('selectedRows'));
Finally, re-highlight stored row indexes when the dataTable is initialised :
var table = $('#example').DataTable({
initComplete : function() {
if (!Array.isArray(selectedRows)) {
//selectedRows does not exists in localStorage or is messed up
selectedRows = [];
} else {
var _table = this.api();
selectedRows.forEach(function(index) {
//for some reason to$() doesnt work here
$(_table.row(index).node()).addClass('highlight');
})
}
}
});
demo -> http://jsfiddle.net/f3ghvz4n/
Try the demo, highlight some rows and then reload the page. Notice that this works on a paginated dataTable as well!
Update. When you are using a AJAX datasrc reloaded each 30 secs, I think you could skip the initComplete and just rely on the draw.dt event :
var table = $('#example').DataTable();
$('#example').on('draw.dt', function() {
if (!Array.isArray(selectedRows)) {
selectedRows = [];
} else {
selectedRows.forEach(function(index) {
$(table.row(index).node()).addClass('highlight');
})
}
})
Completely untested, but cannot see why it shouldnt work.
This should do the trick:
$('#id tbody > tr').eq(rowindex)
or
$('#id tbody > tr').eq(rowindex).children().addClass('myClass');

Categories