How to get <tr> count in HTML table - using Jquery? - javascript

I am using Jquery Datatables to achieve search and sort functionality on HTML table <table>.
I have more then 100 rows in <table> and I used iDisplayLength=6 attribute to display on 6 records at the same time and enabled paging functionality for more records.
The problem is: I want to count that how many <tr> in <table> using jquery.
I used follwing code for that but it gives count 6 <tr> always because I used DisplayLength=6.
But I want actual count of <tr>
JavaScript
$(document).ready(function () {
$("#ContentPlaceHolder1_grdRX").dataTable({
"iDisplayLength": 6,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false
});
});
function getCount() {
alert($('#ContentPlaceHolder1_grdRX tr').length);
}
How can I get a count of all the rows?

It looks like DataTables is removing the rows that aren't on the current page from the DOM, so you aren't going to be able to count them with a jQuery selector. You'll have to use the DataTables API, specifically the fnGetHiddenNodes function:
var table = $('##ContentPlaceHolder1_grdRX').dataTable();
$('#button').click( function () {
var hidden = table.fnGetHiddenNodes();
alert( hidden.length +' nodes were returned' ); } );

Related

How can I extract a selected row's data on Datatables

I have initialised a simple Datatable:
//initialise table
var dataTable = $('#example').DataTable({
searching: false,
responsive: true
});
//hide unnecessary columns
dataTable.columns(1).visible(false);
dataTable.columns(2).visible(false);
dataTable.columns(3).visible(false);
dataTable.columns(4).visible(false);
dataTable.columns(5).visible(false);
dataTable.columns(6).visible(false);
dataTable.columns(7).visible(false);
dataTable.columns(8).visible(false);
It can contain any number of records but I would like to take the values from all of the columns (only 1 is displayed to the user) and insert them into input fields (which may or may not be visible). I have successfully been able to select the rows using:
$('#example tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
dataTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
I have been looking into the Datatables API, row(), cells() etc and whilst I can view the data() method I simply can't see how to extract data from EACH cell on the row into the input text fields on the same webpage. I have also looked at fnGetSelectedData but I didn't get far as it always returned undefined via the console.
To explain the use case, it's essentially an Address Lookup. Each column in the table represents part of the address, I want to take the cells from the selected row and insert it into the form as a users selected address.
Any help is appreciated
SOLUTION
Use the code below to get data for the selected row:
var data = $('#example').DataTable().row('.selected').data();
Then you can populate your input fields as shown below:
$('#name').val(data[0]);
$('#email').val(data[1]);
See this jsFiddle for demonstration.
NOTES
You can simplify your initialization code:
var dataTable = $('#example').DataTable({
searching: false,
responsive: true
columnDefs: [
{
targets: [1,2,3,4,5,6,7,8],
visible: false
}
]
});
To get an object with the values use:
yourTableVariable.rows({ selected: true }).data();
Then you can do something like this to get specific value(example id):
yourTableVariable.rows({ selected: true }).data()[0].id;

how to select all checkbox in Datatables

I want to select all my checkbox
I have an input in header of datatables like this
<th style="width: 25%" ><input type="checkbox" name="checkall" class="select-checkall" id="checkall" value=""></th>
i use it like this to checked it but only work in the page that iam
$("#checkall").click(function(){
$(':checkbox').prop('checked', true);
});
check this fiddle http://jsfiddle.net/juxHn/46/
jQuery will not be able to find checkboxes in other pages than the current one because DataTables somehow hides them (maybe removes them from DOM?)
Please refer to DataTables API to access your table cells irrespective of which ones are currently shown or not / of which page you are on.
In your case, you could do:
// Use "DataTable" with upper "D"
oTableStaticFlow = $('#flow-table').DataTable({
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
});
$("#flowcheckall").click(function () {
var cells = oTableStaticFlow.column(0).nodes(), // Cells from 1st column
state = this.checked;
for (var i = 0; i < cells.length; i += 1) {
cells[i].querySelector("input[type='checkbox']").checked = state;
}
});
Demo: http://jsfiddle.net/juxHn/47/

How to make DataTables show only subset of columns then allowing others to appear by toggling

I have the following JS
$(document).ready(function() {
var table = $('#example').DataTable( {
"scrollY": "200px",
"paging": false
} );
$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column( $(this).attr('data-column') );
// Toggle the visibility
column.visible( ! column.visible() );
} );
} );
JSFiddle or DataTablesExample
Which produce the following table that allows user to toggle the six columns by clicking on the link next to Toggle column.
What I want to do then is to make the table to show only Name and Position column as default and hide the rest of columns. Only when the user toggle their preferred other columns then they will appear. How can this be achieved?
In reality I have ~50 columns to show. Currently it overflow the page.
Not sure what's the best way to display such case.
With ColVis
You need to use ColVis extension for Datatables.
Most likely you would want to hide some columns initially, you can do that using the code below.
var oTable = $('#example').DataTable({
"dom": 'C<"clear">lfrtip',
"columnDefs" : [
{ "targets": [4,5], "visible": false }
]
});
See this JSFiddle for demonstration.
Also ColVis extension allows you to group columns and toggle group visibility instead of individual columns which could be helpful if you have 50 fields.
If you have that many fields, I would also consider showing extra details or responsive extension along with ColVis, you may be able to integrate these together.
Without ColVis
It can also be done without ColVis using the code below:
HTML
<p>Toggle: Start date | Salary</p>
<table id="example" class="display" cellspacing="0" width="100%">
<!-- skipped -->
</table>
JavaScript
var oTable = $('#example').DataTable({
"dom": 'lfrtip',
"columnDefs" : [
{ "targets": [4,5], "visible": false }
]
});
$('a.column-toggle').on('click', function(e){
var column = oTable.column($(this).data('id'));
column.visible(!column.visible());
e.preventDefault();
});
See this JSFiddle for demonstration.
You could show the remaining information in the child table
see: https://www.datatables.net/examples/api/row_details.html

do tags into clickable tags filters for jquery table - yadcf

I see this filtering yadcf demo for Datatables: Live Demo
You can filter table by tags but you can't click on Tag1 or Tag2 for use them like filtering table results and return only rows that have Tag1 or Tag2.
is possible use tag inside table like a cliccable tags filters mode?
Which code must edit/add in jquery.datatables.yadcf.js?
In the demo above this is part of code. How implement my feature request in column_number: 4 or tag column?
$(document).ready(function () {
'use strict';
//----------------------------------------------
// this is the code for column tag
//----------------------------------------------
oTable = $('#example').dataTable({
"bJQueryUI": true,
"bStateSave": true
}).yadcf([{
......
......
{
column_number: 4,
select_type: 'select2',
select_type_options: {
width: '150px'
placeholder: 'Select tag',
allowClear: true // show 'x' (remove) next to selection inside the select itself
},
column_data_type: "html",
html_data_type: "text",
filter_reset_button_text: false // hide yadcf reset button
}]);
SyntaxHighlighter.all();
Which of these parameters must be edited?
column_number
filter_type
custom_func
data
column_data_type
text_data_delimiter
html_data_type
filter_container_id
filter_default_label
filter_reset_button_text
enable_auto_complete
sort_as
sort_order
date_format
ignore_char
filter_match_mode
select_type
select_type_options
case_insensitive
filter_delay
It can be achieved in the following ways
1) call this code upon page ready (note that your selector probably will be different)
$('#example').on('click',".label.lightblue", function () {
yadcf.exFilterColumn(oTable, [[4, $(this).text()]]);
});
2) attach onclick event to your "tags" , something like this onclick="yadcf.exFilterColumn(oTable, [[4, 'Tag1']]);"

DataTable : How to hide the pagination and only show it as need?

I have 2 tables that are using DataTable jQuery Plug-in.
I wondering if there is a way to hide my pagination on the bottom right of my table.
Note:
Only show the pagination when I need one.
Hide the pagination when the query results is less than 10.
Use drawCallback option to handle DT draw event and show/hide pagination control based on available pages:
$('#table_id').dataTable({
drawCallback: function(settings) {
var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
pagination.toggle(this.api().page.info().pages > 1);
}
})
$('#dataTable_ListeUser').DataTable( {
//usual pager parameters//
"drawCallback": function ( settings ) {
/*show pager if only necessary
console.log(this.fnSettings());*/
if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
$('#dataTable_ListeUser_paginate').css("display", "block");
} else {
$('#dataTable_ListeUser_paginate').css("display", "none");
}
}
});
Use 'drawCallback' to solve this problem.
1.On the webpage, use developer tool to inspect the 'previous' button, then you will find a div element that wraps both the 'previous' and 'next' buttons. DataTables automatically assigned an id to this div based on your html table element's id.
For example, I have a table with id 'Atable'. In this table, DataTables automatically created a div element with id called 'Atable_paginate' to wrap the previous and next buttons.
2.For drawCallback, we write a function which checks if there is less than 1 page, if so, we hide element by utilising id.
For example, you have set there are 20 records on one page by
pageLength: 20,
which means if there are less then 20 records, we don't need to display 'previous' and 'next' buttons. So we write like below,
drawCallback: function(settings){
if($(this).find('tbody tr').length <= 20){
$('#Atable_paginate').hide();
}
}
3.The initialization of Atable should be like below
var table = $('#Atable').DataTable({
pageLength: 20,
lengthChange: false,
drawCallback: function(settings){
if($(this).find('tbody tr').length <= 20){
$('#Atable_paginate').hide();
}
}
});
4.If there are more than one table on the webpage, apply this method on each table.
You can use fnDrawCallback() method to hide the pagination in dataTable.
var oTable = $('#datatable_sample').dataTable({
"iDisplayLength": 10,
"fnDrawCallback": function(oSettings) {
if ($('#datatable_sample tr').length < 10) {
$('.dataTables_paginate').hide();
}
}
});​
The length which you can define as per the row you want to display in the listing.
$(this) did not work for me, probably because I am using TypeScript. So I used a different approach to get the JQuery element for the table wrapper and the DataTables API. This has been inspired by the answer of BitOfUniverse and tested with DataTables 1.10.
TypeScript:
'drawCallback': (settings: any) => {
// hide pager and info if the table has NO results
const api = new $.fn.dataTable.Api(settings);
const pageCount = api.page.info().pages;
const wrapper = $('#' + settings.sTableId).closest('.dataTables_wrapper');
const pagination = wrapper.find('.dataTables_paginate');
const info = wrapper.find('.dataTables_info');
pagination.toggle(pageCount > 0);
info.toggle(pageCount > 0);
}
You can give options when you create your datables on Javascript
$('.examples').DataTable({
"paging": false
});
All options are listed here:
http://www.datatables.net/reference/option/

Categories

Resources