I want to find a row that has a certain value in one of the cells and apply class. I managed to do that, but problem is that it works only when I get to the page where that value exists.
drawCallback: function( settings ) {
var data = table.rows({ page: 'all' }).data();
$(data).each( function (idx) {
var row = table.row( idx );
if ( row.data().username === 'miko55' ) {
row.nodes().to$().addClass( 'table-success' );
alert(idx);
}
} );
}
I tried with page:'all' but it doesn't change anything.
You need to use Datatables jumpToData() plugin to achieve this. Try this
//jump to particular row in a table
YOUR_TABLE.page.jumpToData('VALUE YOU ARE LOOKING FOR', 0);
//add you CSS class to the row
YOUR_TABLE.rows(function (idx, data, node) {
if(data.YOUR_VALUE === 'VALUE YOU ARE LOOKING FOR') {
return true;
}
}).nodes().to$().addClass('YOUR CSS CLASS');
Related
I need to know how to make my search filter that is with the JS Datatable plugin do a search with the exact value, now when placing the value 1 for example, it returns the numbers 1, 21, 113, 41 etc. It is a simple code only I can not find how to do that ...
I hope you can help
$('#txtFolioFilter').on( 'keyup change clear', function () {
table
.columns(13)
**.search = ( this.value )**
.draw();
} );
You can do this with a custom search function. The following example assumes you are using the standard DataTables global search field - which can be selected using the following jQuery selector:
$('.dataTables_filter input')
Here is the function:
$(document).ready(function() {
var table = $('#example').DataTable( {
// your table initialization here
} );
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
var searchTerm = $('.dataTables_filter input').val();
if (searchTerm.trim() === "") {
return true;
}
var exactMatch = false;
searchData.forEach(function (cellText) {
if (searchTerm === cellText) {
exactMatch = true;
}
});
return exactMatch;
}
);
} );
The following line captures all search events from the main search box:
$.fn.dataTable.ext.search.push(...)
A blank search term will return all records.
Otherwise, for each row, we check each field in the row, and return that row as matched if any of the fields exactly match the search term.
If you want to apply this "exact match" to only one column, then you can adjust the custom filter:
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
var searchTerm = $('.dataTables_filter input').val();
if (searchTerm.trim() === "") {
return true;
}
var match = false;
searchData.forEach(function (cellText, index) {
if (index === 3) {
if (searchTerm === cellText) {
match = true;
}
} else {
// all other columns:
if (cellText.includes(searchTerm)) {
match = true;
}
}
});
return match;
}
);
With this approach, what rows are displayed will depend on what your data looks like across the entire row, of course.
Documentation for the search plug-in is here, for more background.
This is the approach I have tried so far:
$("#ExportPDF").on("click", function() {
var datatable = $('#myTable').DataTable();
if (! datatable.data().any()) {
console.log( 'the table is actually empty' );
}
else{
var table = $('#myTable').DataTable().search('something');
table.button( '.buttons-pdf' ).trigger();
}
});
When my table is empty, it does not export anything, which is perfect for me.
Now when the table contains elements, I do a search on a keyword something; if items are found they export them. But when no information is found it still exports an empty PDF.
How to avoid exporting an empty PDF?
Check the returned array before triggering the button :
else {
var table = $('#myTable').DataTable().search('something');
if( table != "" ){
table.button('.buttons-pdf').trigger();
}
}
$('#tableid').dataTable({
"fnDrawCallback": function () {
var table = $('#tableid').DataTable();
if (table.data().length === 0)
table.buttons('.buttons-html5').attr('disabled', true);
else
table.buttons('.buttons-html5').attr('disabled', false);
}
});
I have a simple DataTable for which I'm adding a class called selected when the user clicks the row:
$("#datatable-buttons tbody").delegate("tr", "click", function (event) {
var $row = $(event.target);
if ($row[0].tagName !== "TR") $row = $row.parent();
$row.toggleClass("selected");
if (event.ctrlKey === false) {
$row.toggleClass("selected");
$row.siblings().removeClass("selected");
}
});
Inside the same function I'm trying to count the rows that have the second column different from ---
var clickedD = 0;
table.rows('.selected').every(function () {
if (this.cell('.selected', 1).data() != "---")
clickedD++;
});
But when there are more than one row selected it counts just the first row with this class. Is there a way to get the number of rows that are selected (have the class selected) with the second cell of each row different from ---?
You can just use the row().data() array. And use the API more heavily. Here is a more simplified version :
table.on('click', 'tbody tr', function() {
table.row(this).nodes().to$().toggleClass('selected');
var count = 0;
table.rows('.selected').every(function() {
if (table.row(this).data()[1] !== '---') count ++;
})
$('#count').text(count+' selected rows with #2 col different from ---')
})
demo -> http://jsfiddle.net/q6d8wqLk/
If you have a JSON based dataSource,, you can use
if (table.row(this).data().secondColData !== '---') count ++;
FYI: delegate() is now deprecated.
I am getting all file upload control through the following code
var fileuploadControls = $( "input[type='file']" );
Now I want to loop thorugh the fileuploadControls and remove if ID is not matching something like this
for(var i=0;i<fileuploadControls .length;++i)
{
if(fileuploadControls[i].id != "A")
{
//remove the item and fileUploadcontrols should be same type of abject as returned by the jquery not an array
}
}
I have tried splice it works but it returns an array which I don't want after removal of item fileuploadControls should of same type of object as it was before removal only one item should be less
Can someone help in coding this
I am using the following celltemplate in Angular ui-grid
cellTemplate: '<div class="ui-grid-cell-contents"> <input name="curfewRegularizationFile" id="curfewRegularizationFile" type="file" class="k-state-disabled" /></div>',
and in javascript file I am doing this
fileuploadControls[i].kendoUpload({ // Do something as per kendo});
You can can create a function to remove element
for(var i=0;i<fileuploadControls .length;++i)
{
if(fileuploadControls[i].id != "A")
{
remove(fileuploadControls[i].id);
}
}
function remove(id) {
return (el=document.getElementById(id)).parentNode.removeChild(el);
}
Remove from DOM too:
In your loop you can do it this way:
for(var i = 0; i < fileuploadControls.length; ++i ) {
if( fileuploadControls[i].id !== "A" )
fileuploadControls.eq(i).remove();
}
But I would do it in the jQuery way, in a loop with jQuery objects you can do it with each. But this is even the slowest option to choose.
fileuploadControls.each(function() {
if( $(this).attr("id") !== "A" )
$(this).remove();
});
Or directly as a sub-selector:
fileuploadControls.not("#A").remove();
Remove only from Object:
By better initial selector:
var fileuploadControls = $("input[type=file]:not(#A)");
By trim down the jQuery object:
fileuploadControls = fileuploadControls.not("#A");
By filter:
fileuploadControls = fileuploadControls.filter(function() {
return $(this).attr("id") !== "A";
});
Currently I have this code to delete a table row:
var remove = document.getElementById(dataID); (this is the id of an object in the row I wish to hide)
if(remove!=null){
var v = remove.parentNode.parentNode.rowIndex;
document.getElementById(tid).deleteRow(v); (tid is the table id, not the row id)
}
However, instead of delete it, I'd just like to hide it. What's a good way to do this?
Also, in the future, I'm going to want to 'unhide' it at user request, so how can I check if it has been hidden? The if(remove!=null) is what checked if a row was already removed, so I'd need something similar.
Thank you for your time.
document.getElementById(tid).children[dataID].style.display = 'none';
You may need -1 on dataID
And block to show it again (or inline or whatever it originally was, for a div it's block).
JQuery:
$('#'+tid+':nth-child('+dataID+')').hide();
My own approach, in plain JavaScript:
function toggleRow(settings) {
// if there's no settings, we can do nothing, so return false:
if (!settings) {
return false;
}
// otherwise, if we have an origin,
// and that origin has a nodeType of 1 (so is an element-node):
else if (settings.origin && settings.origin.nodeType) {
// moving up through the ancestors of the origin, until
// we find a 'tr' element-node:
while (settings.origin.tagName.toLowerCase() !== 'tr') {
settings.origin = settings.origin.parentNode;
}
// if that tr element-node is hidden, we show it,
// otherwise we hide it:
settings.origin.style.display = settings.origin.style.display == 'none' ? 'table-row' : 'none';
}
// a simple test to see if we have an array, in the settings.arrayOf object,
// and that we have a relevant table to act upon:
else if ('join' in settings.arrayOf && settings.table) {
// iterate through that array:
for (var i = 0, len = settings.arrayOf.length; i < len; i++) {
// toggle the rows, of the indices supplied:
toggleRow({
origin: table.getElementsByTagName('tr')[parseInt(settings.arrayOf[i], 10)]
});
}
}
}
// you need an up-to-date browser (you could use 'document.getElementById()',
// but I'm also using 'addEventListener()', so it makes little difference:
var table = document.querySelector('#demo'),
button = document.querySelector('#toggle');
// binding a click event-handler to the 'table' element-node:
table.addEventListener('click', function (e) {
// caching the e.target node:
var t = e.target;
// making sure the element is a button, and has the class 'removeRow':
if (t.tagName.toLowerCase() === 'button' && t.classList.contains('removeRow')) {
// calling the function, setting the 'origin' property of the object:
toggleRow({
origin: t
});
}
});
// binding click-handler to the button:
button.addEventListener('click', function () {
// calling the function, setting the 'arrayOf' and 'table' properties:
toggleRow({
'arrayOf': document.querySelector('#input').value.split(/\s+/) || false,
'table': table
});
});
JS Fiddle demo.
References:
document.querySelector().
e.target.addEventListener().
Node.nodeType.
String.split().
As you've asked for a jQuery solution...how about
var $remove = $('#' + dataID);
if ($remove) {
$remove.closest('tr').closest().hide();
}
?