Datatable hide column while searching [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I have created a datatable (fiddler link provided) with search feature enabled. When I search the table filters the data. In the example, if we search for "Software", it gives me 5 rows and the "office" column doesn't have the data in it. How could I hide this column or any other if it doesn't have the data?
[Fiddler Link](https://jsfiddle.net/vhyb039f/) Fiddler Link
I searched in google but couldn't find any with this kind of scenario.
I tried to add hideEmptyCols but it still shows the column.

Please try this code
$(document).ready(function () {
$('#example').dataTable({
hideEmptyCols: {
columns: [2, 3, 4],
perPage: true,
emptyVals: ['-']
}
});
var hidecolumn = [];
var table = $('#example').DataTable();
table.on('search.dt', function (e) {
e.preventDefault();
// Get the column API object
table.rows().every(function () {
var d = this.data();
d.counter++; // update data source for the row
if ($.inArray("-", d) !== -1){
hidecolumn.push($.inArray("-", d));
}
});
$(hidecolumn).each(function (index,val) {
var column = table.column(val);
// Toggle the visibility
column.visible(!column.visible());
});
});
});
And here some reference link

Related

How to know/capture the Detail Grid ID of the specific detail grid you are in? (ag-grid javascript)

I have a Master-Detail ag-grid. One column has checkboxes, (checkboxSelection: true). The details grid have a custom status panel with a button. When the user clicks the button in any specific Detail grid, I don't know how to get the SelectedRows from just that one specific detail grid.
The problem is they might leave multiple details displayed/open, and then looping over each Detail Grid will include results from all open grids. I'm trying to isolate to just the grid where the user clicked the button.
I tried looping through all displayed/open detail grids to get the Detail grid ID. But I don't see any info in this that shows me which one they clicked the button in.
I tried in the button component to see if, in the params, there is anything referencing the detailgrid ID that the button is in, but I did not see anything there either.
This is the button component:
function ClickableStatusBarComponent() {}
ClickableStatusBarComponent.prototype.init = function(params)
{
this.params = params;
this.eGui = document.createElement('div');
this.eGui.className = 'ag-name-value';
this.eButton = document.createElement('button');
this.buttonListener = this.onButtonClicked.bind(this);
this.eButton.addEventListener("click", this.buttonListener);
this.eButton.innerHTML = 'Cancel Selected Records <em class="fas fa-check" aria-hidden="true"></em>';
console.log(this.params);
this.eGui.appendChild(this.eButton);
};
ClickableStatusBarComponent.prototype.getGui = function()
{
return this.eGui;
};
ClickableStatusBarComponent.prototype.destroy = function()
{
this.eButton.removeEventListener("click", this.buttonListener);
};
ClickableStatusBarComponent.prototype.onButtonClicked = function()
{
getSelectedRows();
};
Here is the code to loop through and find all open detail grids:
function getSelectedRows()
{
this.gridOptions.api.forEachDetailGridInfo(function(detailGridApi) {
console.log(detailGridApi.id);
});
I was able to work this out, so thought I'd post my answer in case others have the same issue. I'm not sure I took the best approach, but it's seemingly working as I need.
First, I also tried using a custom detail cell renderer, as per the documentation, but ultimately had the same issue. I was able to retrieve the DetailGridID in the detail onGridReady function--but couldn't figure out how to use that variable elsewhere.
So I went back to the code posted above, and when the button was clicked, I do a jquery .closest to find the nearest div with a row-id attribute (which represents the the DetailgridID), then I use that specific ID to get the rows selected in just that detail grid.
Updated button click code:
ClickableStatusBarComponent.prototype.onButtonClicked = function()
{
getSelectedRows(this);
};
Updated getSelectedRow function:
function getSelectedRows(clickedBtn)
{
var detailGridID = $(clickedBtn.eButton).closest('div[row-id]').attr('row-id');
var detailGridInfo = gridOptions.api.getDetailGridInfo(detailGridID);
const selectedNodes = detailGridInfo.api.getSelectedNodes()
const selectedData = selectedNodes.map( function(node) { return node.data })
const selectedDataStringPresentation = selectedData.map( function(node) {return node.UniqueID}).join(', ')
console.log(selectedDataStringPresentation);
}

Sometimes the list connects other times it doesn't

Sometimes the lists connect and you can transfer between them. Other times it doesn't connect. At all times you can sort within each list, but sometimes not between them. I can't figure it out.
$('#questions .survey-page ul').sortable({
items: 'li:not(.placeholder)',
sort: function() {
$(this).removeClass('ui-state-edit'); // While sorting we do not want edit buttons to show.
},
update: function() {
refreshAllDetails(); // Update survey with the new details.
},
connectWith: '#questions .survey-page ul'
});
#question is a tag that multiple .survey-page children are put into. Each .survey-page has a ul with multiple li entries. It is this ul that I am trying to link between .survey-pages.
EDIT: As per request:
/**
* Saves the order of questions, then saves the details of all questions to server.
*/
function refreshAllDetails() {
saveOrder();
saveAllToDatabase();
}
/**
* Saves the details of all questions to server.
*/
function saveAllToDatabase() {
// Go through each page.
$("#questions").find(".survey-page").each(function() {
var surveypage = this;
// Save metadata for current page.
// Go through each question on page.
$(this).find(".questiontypestuffp").each(function() {
// Get the answers for a particular question, including meta-data for question.
var result = callWidget($(this), "getEditedAnswers");
// Get the order of the question listed on page.
result.questionorder = $(this).attr('ordervalue');
result.pageno = $(surveypage).attr("ordervalue");
// Save the question's order to its associated widget.
callWidget($(this), "setData", result);
// Update the question in database.
$.ajax({dataType: "json", url: "index.php?option=com_survey&loadorsave=update&view=surveydata&layout=edit&id=" + $("#itemid").val() + "&tmpl=component&format=json&questionvalues=" + encodeURI(JSON.stringify(result)), success: function(callback) {
}});
// Turn off edit mode.
setEditModeOff();
});
});
}
/**
* Refreshes order values with regard to their position on page. This rewrites the order values as they appear.
*/
function saveOrder() {
var pageorder = 0;
// GO through each page.
$("#questions").find(".survey-page").each(function() {
var questionorder = 0;
// Rewrite page order.
var currentPage = ++pageorder;
$(this).attr('ordervalue', currentPage);
// Rewrite each question's order on page.
$(this).find(".questiontypestuffp").each(function() {
$(this).attr('ordervalue', ++questionorder);
});
});
}
I've solved my own problem here. The class I was removing was actually required to recognize drag and drop operations, hence 'ui-state-edit'. By dynamically updating this class to/from the DOM element, this was affecting whether the list item was able to be transferred between lists. As a brief - drag and drop was rejecting the list item since it didn't have a valid class name.

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.

Single check box selection with jquery datatable

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

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/

Categories