Change datatables ScrollY clicking on button - javascript

I have a dataTable like this one:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT something";
$get_result = sqlsrv_query($conection,$query);
while($row = sqlsrv_fetch_array($get_result)){
$dest = $row['dest'];
$num1 = $row['num1'];
$num2 = $row['num2'];
$num3 = $row['num3'];
echo "<tr>
<td class='hidden'>{$dest}</td>
<td>{$num1}</td>
<td>{$num2}</td>
<td>{$num3}</td>
</tr>";
}
sqlsrv_close($conection);
?>
</tbody>
</table>
<div class="the_button">
View All
</div>
And my js for the dataTable :
$(document).ready(function() {
$('#example').DataTable( {
"scrollY": "100px", // Here
"scrollCollapse": true,
"paging": false,
"ordering": false,
"info": false,
initComplete: function () {
this.api().columns([0]).every( function () {
var column = this;
var select = $('<select><option value="">Select Option</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>' )
} );
} );
}
} );
} );
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
So lets go in my problem.
I want when the button view all is clicked to change the ScrollY from 100px to auto value or 500px e.g.
I tried many examples found on community but not chance.
I tried by changing the css with js but not luck.
$('.dataTables_scrollBody').css('height', 400); Not working for me this one
Also I tried to leave the ScrollY blank and add the height with CSS and javascript but still no luck.
Any ideas?
Thanks

I have experienced a similar problem, but this was my solution:
$("#myTable").DataTable({scrollY: 100});
// ...
$("#myTable").DataTable({retrieve: true}).destroy();
// ...
$("#myTable").DataTable({scrollY: 200});
I did this because dataTables are intended to run with a single initialisation. The retrieve option on the second executable line above only returns the instance without re-initialisation the dataTable, then I call destroy on it - which reverts all the changes the plugin has made to the DOM. a Simple re-initialisation was the dirty fix that changed the height as per required.

Related

Adding select menu to multiple tables with jquery data tables pluglin

I've got two tables (table1,table2) that are structurally the same, but fed from different sources. Both tables share the class 'display' which I use to initialise the plugin for both tables. This works great for the most part, however the column filters select menu for table2 is duplicated on table1.
I've tried to fix this by using 'this' keyword to indicate a particular instance of the toolbar each of the filters need applying to, but not had much success.
The code that works is:
HTML:
<table id="table1" class="display table-striped table-borded table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Report Name</th>
<th>Year</th>
<th>Montly Snapshot</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date of Last Refresh --var from warehouse-- </th>
</tr>
</tfoot>
</table>
<table id="table2" class="display table-striped table-borded table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Report Name</th>
<th>Year</th>
<th>Montly Snapshot</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date of Last Refresh --var from warehouse-- </th>
</tr>
</tfoot>
</table>
JS:
//initialise data tables plugin and apply custom settings.
var reportstable = $('table.display').DataTable({
"sDom": '<"toolbar">Bfrtlp',
"searchCols": [
null, {
'sSearch': 'Current'
}
],
language: {
search: "_INPUT_",
searchPlaceholder: "Search for a Report..."
},
// create select form controls
initComplete: function() {
this.api().columns([1, 2]).every(function() {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($('.toolbar'))
.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>')
if ($('#info').css('display') == 'block') {
$("#reports_wrapper").css('display', 'none');
}
// add bootstrap classes and placeholder property to form controls to add style
$('.toolbar select').addClass('selectpicker');
$('.dt-button').addClass('btn btn-danger').removeClass('dt-button');
$('.toolbar select').attr('id', 'year');
$('#year').prop('title', 'Financial Year');
$("#year option:contains('Current')").remove();
$('.toolbar select:nth-of-type(2)').attr('id', 'month');
$('#month').prop('title', 'Monthy Snapshot');
$("#month option:contains('undefined')").remove();
});
});
},
// create clear filter button
buttons: [
{
text: 'Clear Filters',
action: function(e, dt, node, config) {
$('select').val('').selectpicker('refresh');
// set Current Year as default filter
reportstable
.search('')
.columns([1]).search('Current')
.columns([2]).search('')
.draw();
}
}
],
//hide specified columns
"columnDefs": [
{
"targets": [1],
"visible": false,
"searchable": true
}, {
"targets": [2],
"visible": false,
"searchable": true
}
]
});
I've updates your jsfiddle and created a new jsfiddle. It's now appending 2 select menus in both tables's wrapper div. I've found why it's appending 4 select menus instead of 2 on the table1's wrapper div. It's because of this code: .appendTo($('.toolbar')). When initComplete callback function is called for table1 there is only one div with class=toolbar, and when the initComplete callback function is called for table2 there is two div with class=toolbar, one in table1's wrapper div and one in table2's wrapper div. that's why on table2's initComplete callback function it append select menus to all divs with class=toolbar. We should rather append to the current table wrapper's div with class=toolbar.

How can I duplicate a row in DataTables (jQuery DataTables plugin)?

I found out how to delete a row with this jQuery code. While clicking on a td with the class delete and a garbage icon.
HTML
<table id="foo" class="display" cellspacing="0" width="100%">
<tbody>
<tr>
<td>Foo1</td>
<td>Foo2</td>
<td>Foo3</td>
<td class="delete">IMAGE src here</td>
<td><img src="http://placehold.it/20x20"></td>
</tr>
</tbody>
JAVASCRIPT
$('#foo tbody').on( 'click', 'tr .delete', function () {
$(this).closest('tr').fadeOut("slow", function(){
$(this).remove();
})
} );
But I did not find anything about duplicating rows. I just want to click on a td with another icon in it and the row is duplicated below.
To duplicate a row, you'll need to copy all of its data into an array, then call row.add() to insert this data as a new row.
Something like:
<table id="foo" class="display" cellspacing="0" width="100%">
<tbody>
<tr>
<td>Foo1</td>
<td>Foo2</td>
<td>Foo3</td>
<td class="delete">IMAGE src here</td>
<td class="copy">IMAGE src here</td>
<td><img src="http://placehold.it/20x20"></td>
</tr>
</tbody>
$('#foo tbody').on( 'click', 'tr .copy', function () {
var row_data = [];
$(this).closest('tr').find('td').each(function() {
row_data.push($(this).text());
});
// you'll need a reference to your DataTable here
table.row.add(row_data).draw();
});
To get a reference to your DataTable, assign the result of the DataTable() method to a var.
$(document).ready(function() {
var table = $('#foo).DataTable( { "paging": false, "info": false });
// set up your event handlers, etc.
});
If you append a row with jQuery instead of DataTables method like row.add(), you'll lose the row when you sort or page the table.
Here's the jQuery that adds a row duplicate right underneath it, where DataTables is concerned. It has a caveat that this method may not retain any sorting or filtering set by the user.
$('#formtable tbody').on( 'click', 'button.btn-success', function () {
//destroy instance of DataTables
table.destroy(false);
//script assumes button is clicked on the line that needs to be duplicated
var btn = this;
//copy and insert row right below the original
var line = $(btn).parents('tr');
line.after(line.clone());
//since clone retains only input field values, but not dropdown selections,
//each dropdown value must be assigned individually
line.next().find("select.shape").val(line.find("select.shape").val());
line.next().find("select.material").val(line.find("select.material").val());
line.next().find("select.supplied").val(line.find("select.supplied").val());
//re-creating DataTables instance
//notice that "table" has no "var" in front - that's because it is pre-defined.
table = $('#formtable').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": "_all"
} ],
"paging": false,
"info": false,
"ordering": true,
"searching": false,
"rowReorder": true
});
//"Index Column" values re-calculation
table.column(0).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
});
});
Hope this helps.
Try this:
HTML
<table id="foo" class="display" cellspacing="0" width="100%">
<tbody>
<tr>
<td>Foo1</td>
<td>Foo2</td>
<td>Foo3</td>
<td class="delete">IMAGE src here</td>
<td class="duplicate"><img src="http://placehold.it/20x20"></td>
</tr>
</tbody>
</table>
SCRIPT
$('#foo tbody').on( 'click', 'tr .delete', function () {
$(this).closest('tr').fadeOut("slow", function(){
$(this).remove();
})
} );
$('#foo tbody').on( 'click', 'tr .duplicate', function () {
var myTr = $(this).closest('tr');
var clone = myTr.clone();
myTr.after(clone);
} );

Why won't DataTable redraw after manual search

I have a table which I would like to search manually. After looking at the API, I see that I can just do:
table.search(somestring).draw();
and this should search the table and redraw it, or so I assume.
$(document).ready(function(){
var table = $('table').DataTable({
searching: false,
paging: false,
info: false
});
// add a bunch of rows
for(var i=0; i<20; i++){
table.row.add([
"test "+i, "best "+i, "rest "+i
]);
}
// draw the table
table.draw();
// why won't table redraw with only rows containing 15?
table.search('15').draw();
// this doesn't work either
/*
$('input').on( 'keyup click', function () {
filterColumn( 1 ); // filter only first column
} );
*/
});
function filterColumn ( i ) {
console.log( $('input').val() );
$('table').DataTable().column( i ).search(
$('input').val()
).draw();
}
HTML:
<input>
<table>
<thead>
<tr>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Plunker: http://plnkr.co/edit/BlwWWw7mlpde4vKqoX2q?p=preview
You have searching functionality disabled with searching: false, see searching option for more details.
You need to enable searching with searching: true or by removing this option in order for search() method to work.
If you just want to hide filtering control, use dom: 'lrtip', see dom option for more details.

How to update DataTables DOM?

I am using Datatables for a review system, An user can grade each item by clicking on stars(1 to 5).
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="tabela-disciplinas-preferencia">
<thead>
<tr>
<th>Semestre</th>
<th>Curso</th>
<th>Disciplina</th>
<th>Nível de Interesse</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Engenharia de Software</td>
<td>Redes</td>
<td>
<div class="rating" valor="0">
<span valor="5">☆</span><span valor="4">☆</span><span valor="3">☆</span><span valor="2">☆</span><span valor="1">☆</span>
</div>
</td>
</tr>
....
</tbody>
</table>
My JS
$(document).ready(function() {
$('#tabela-disciplinas-preferencia').dataTable( {
"sPaginationType": "bootstrap"
} );
});
However when an user click to grade one item, I change valor attribute in rating div but datatables doesn't update their values internally.
Click rating event
$(document).ready(function() {
$('div.rating span').click(function(){
starR= new StarRating( $(this).parent());
starR.changeValue($(this).attr('valor'));
//Get TR Element
aPos = oTable.fnGetPosition( $(this).parent().parent().get(0) );
aData = oTable.fnGetData( aPos[0] );
//Get rating div
rating = aData[3];
aData[3] = $(rating).attr('valor', $(this).attr('valor'));
// ????
oTable.fnUpdate(aData[3]);
});
});
How can I update datatables DOM? I already got data and changed value but how can I update back to oTable?
Changing values and inserting back to aData already update oTable
$('div.rating span').click(function(){
starR= new StarRating($(this).parent());
starR.changeValue($(this).attr('valor'));
//update oTable row data
aPos = oTable.fnGetPosition( $(this).parent().parent().get(0) );
aData = oTable.fnGetData( aPos[0] );
aData[3] = $(aData[3]).attr('valor', starR.getValue());
});
That's solution I have found and seems working pretty well.
I know it's been a minute, but a simple alternative.
$('div.rating span').click(function () {
//Invalidate Row after DOM manipulation
var parentRow = $(this).closest('tr');
$('#your-table').DataTable().row(parentRow).invalidate().draw();
}
You can invalidate row(s) or column(s) that have been changed and the table will update itself. This method will keep search criteria intact.

Jquery Datatables - Make whole row a link

This maybe simple, but cant seem to figure it out. Using jquery datatables how can I make each row clickable to just link to a normal page? So if someone moused over any of the row the whole row will hightlight and be clickable and link to whatever url I would want it to link to when clicked.
I've use the fnDrawCallback parameter of the jQuery Datatables plugin to make it work. Here is my solution :
fnDrawCallback: function () {
$('#datatable tbody tr').click(function () {
// get position of the selected row
var position = table.fnGetPosition(this)
// value of the first column (can be hidden)
var id = table.fnGetData(position)[0]
// redirect
document.location.href = '?q=node/6?id=' + id
})
}
Hope this will help.
This did it for me using the row callback.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
$(nRow).click(function() {
document.location.href = 'www.google.com';
});
},
$('#myTable').on( 'click', 'tbody tr', function () {
window.location.href = $(this).data('href');
});
where #myTable is the ID of the table, and you need put the href in the tr, like that:
<tr data-href="page.php?id=1">
<th>Student ID</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
It's simple enough to do this with a vanilla <table>, but I don't see why this wouldn't work with a jQuery DataTables one either.
$('#myTableId').on('click', 'tbody > tr > td', function ()
{
// 'this' refers to the current <td>, if you need information out of it
window.open('http://example.com');
});
You'll probably want some hover event handling there as well, to give users visual feedback before they click a row.
You can also use the DataTables plugins api which allows you to create custom renderers.
Very cool: JS addon here
And using the fnDrawCallback
fnDrawCallback: function() {
this.rowlink();
},
You can do that to make row clickable :
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#myTable').dataTable({
"ajax" : "getTable.json",
"fnInitComplete": function ( oSettings ) {
//On click in row, redirect to page Product of ID
$(oTable.fnGetNodes()).click( function () {
var iPos = oTable.fnGetPosition( this );
var aData = oSettings.aoData[ iPos ]._aData;
//redirect
document.location.href = "product?id=" + aData.id;
} );
},
"columns" : [ {
"data" : "id"
}, {
"data" : "date"
}, {
"data" : "status"
}]
});
});
</script>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
I think it will be like that
$('#invoice-table').dataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var slug = $(nRow).data("slug");
$(nRow).attr("href", "/invoices/" + slug + "/");
$(nRow).css( 'cursor', 'pointer' );
$(nRow).click(function(){
window.location = $(this).attr('href');
return false;
});
}
});
And the table row like that
<tr class="invoice_row" data-slug="{{ invoice.slug }}">
<td>{{ invoice.ref }}</td>
<td>{{ invoice.campaign.name }}</td>
<td>{{ invoice.due_date|date:'d-m-Y' }}</td>
<td>{{ invoice.cost }}</td>
<td>
<span class="label label-danger">Suspended</span>
</td>
</tr>
This worked fine with me
**I have used a simple solution for this. Add onclick on tr and you are done. Tested with jquery datatable **
<tr onclick="link(<?php echo $id; ?>)">
function link(id){
location.href = '<?php echo $url ?>'+'/'+id;
}
Recently I had to deal with clicking a row in datatables.
$(document).ready(function() {
$("#datatable tbody tr").live( 'click',function() {
window.open('http://www.example.com');
} );
} );

Categories