Populate bootstrap-select with array of options - javascript

I created a table using datatables and on footer I added anempty dropdown select using Bootstrap-select as below :
<tfoot>
<tr>
<th><select class="selectpicker" multiple></select></th>
</tr>
</tfoot>
When my datatable is created, I want to add the distinct values of that column as options in my select.
The issue is : the datatable is drawn without errors but the select is not populated. It still shows empty but when i use inspect on browser I see the options are already inside the select.
I used emptybefore append and tried html instead of append but still not showing the options. I also tried footerCallback instead of initComplete.
When I add the options manually inside my select in the html, it works fine. it looks like in datatable the footer is loaded before the body that's why it's not showing the options when it's displayed before the body is ready.
Any suggestions please how I could fixe it ? Thank you very much.
$(document).ready(function() {
$('.selectpicker').selectpicker();
$('#example').DataTable({
"lengthChange": false,
"info": false,
"paging": false,
"searching": false,
initComplete: function () {
this.api().columns().every( function () {
var column = this;
column.data().unique().sort().each( function ( d, j ) {
$('.selectpicker').append( '<option value="'+d+'">'+d+'</option>' ) } );
} ); } }); });
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script>
<table id="example" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr><td>Austria</td></tr>
<tr><td>Japan</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>Finland</td></tr>
<tr><td>India</td></tr>
<tr><td>USA</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>France</td></tr>
<tr><td>Austria</td></tr>
</tbody>
<tfoot>
<tr>
<th><select class="selectpicker" multiple></select></th>
</tr>
</tfoot>
</table>

Your mistake was initiating your selectpicker before populating it with options, whereas the opposite is recommended in their reference docs.
Following is a fixed live-demo:
$('#example').DataTable({
lengthChange: false,
info: false,
paging: false,
searching: false,
initComplete: function(){
const table = this.api();
table.columns().every(function(){
const title = $(this.header()).text();
const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
$('.selectpicker').append(options).selectpicker()
});
}
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" /><link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css"><script src="https://code.jquery.com/jquery-3.5.1.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script><script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script><script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script><table id="example" class="table table-bordered" style="width:100%"><thead><tr><th>Country</th></tr></thead><tbody><tr><td>Austria</td></tr><tr><td>Japan</td></tr><tr><td>Sweden</td></tr><tr><td>Finland</td></tr><tr><td>India</td></tr><tr><td>USA</td></tr><tr><td>Sweden</td></tr><tr><td>France</td></tr><tr><td>Austria</td></tr></tbody><tfoot><tr><th><select class="selectpicker" multiple></select></th></tr></tfoot></table>

You will need to initialize the selectpicker after you append the data not before.
$(document).ready(function() {
$('#example').DataTable({
"lengthChange": false,
"info": false,
"paging": false,
"searching": false,
initComplete: function () {
this.api().columns().every( function () {
var column = this;
column.data().unique().sort().each( function ( d, j ) {
$('.selectpicker').append( '<option value="'+d+'">'+d+'</option>' ) } );
} ); } });
// initialize the selectpicker after appending options
$('.selectpicker').selectpicker();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script>
<table id="example" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr><td>Austria</td></tr>
<tr><td>Japan</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>Finland</td></tr>
<tr><td>India</td></tr>
<tr><td>USA</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>France</td></tr>
<tr><td>Austria</td></tr>
</tbody>
<tfoot>
<tr>
<th><select class="selectpicker" multiple></select></th>
</tr>
</tfoot>
</table>

Related

how to format date in jQuery DataTables

I am using jQuery DataTables and I have multiple columns with dates, the current data is in this format 2020-06-18 14:32:45.707 and I want to format it and display it as 18/06/2020 14.32.
I applied datetime plugin in DataTables, but still can't make it work.
Currently I am using :
render: function(data) {
return moment(data).format('DD/MM/YYYY HH:mm');
}
Which is working fine. But I want to use render:
render: $.fn.dataTable.render.moment('DD/MM/YYYY HH:mm')
I have included moment.js and datetime.js as the documentation says and I should apply:
$.fn.dataTable.render.moment(to);
My dates are shown as 'invalid date' in my table when i use this method.
below is a demo.
Could you please explain me what am I doing wrong with?:
$.fn.dataTable.render.moment('DD/MM/YYYY HH:mm')
I have the other method working, but I want to learn from my mistakes as I spend much time investigating and couldn't figure out the issue. Thank you very much.
$(document).ready(function() {
$('#example').DataTable({
"columnDefs": [{
//render: $.fn.dataTable.render.moment( 'DD/MM/YYYY HH:mm' )
"render": function(data) {
return moment(data).format('DD/MM/YYYY HH:mm');
},
"targets": 1
}]
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.21/dataRender/datetime.js"></script>
<table id="example" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>date before format</th>
<th>date after format</th>
</tr>
</thead>
<tbody>
<tr>
<td>2020-06-18 14:32:45.707</td>
<td>2020-06-18 14:32:45.707</td>
</tr>
</tbody>
</table>
Your issue is here:
// Argument shifting
if (arguments.length === 1) {
locale = 'en';
to = from;
from = 'YYYY-MM-DD';
}
The default FROM is 'YYYY-MM-DD', you need to specify YOUR source format.
const FROM_PATTERN = 'YYYY-MM-DD HH:mm:ss.SSS';
const TO_PATTERN = 'DD/MM/YYYY HH:mm';
$(document).ready(function() {
$('#example').DataTable({
columnDefs: [{
render: $.fn.dataTable.render.moment(FROM_PATTERN, TO_PATTERN),
targets: 1
}]
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.21/dataRender/datetime.js"></script>
<table id="example" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>date before format</th>
<th>date after format</th>
</tr>
</thead>
<tbody>
<tr>
<td>2020-06-18 14:32:45.707</td>
<td>2020-06-18 14:32:45.707</td>
</tr>
</tbody>
</table>

Click in x editable and empty td

I want to select a td to edit in my table and automatic clean the text of that td.
$('#table').editable({
container: 'body',
selector: 'td.task',
title: 'task',
type: "POST",
showbuttons: true,
type: 'text',
validate: function(value) {
if ($.trim(value) == '') {
return 'Empty!';
}
},
success: function(response) {
}
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.full.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
<table id="table" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Task</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td data-name="task" data-placement="bottom" class="task" data-type="text">001</td>
</tr>
<tr>
<td>2</td>
<td data-name="task" data-placement="bottom" class="task" data-type="text">002</td>
</tr>
</tbody>
</table>
I found this code $('.editable').editable('setValue', null) but only with ID. I dunno how to use in a table the setValue. I hope I explain well. Greetings
You can use this simple way to select a td and clear its text on click.
let td = document.querySelectorAll("td");
for(let i of td) {
i.addEventListener('click', () => {
i.innerHTML = "";
})
}
It will add the event listener on all the tds if you only want to select td with class task then replace the value of querySelectorAll() to "td.task"

sort for dataTable

I am trying to sort in datatable but, i couldn't understand how to do it. let me show what i tired to do with my code.
$(document).ready(function() {
$('#table').DataTable();
} );
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" type="text/css" media="all" />
<table id="table" class="display" style="width:100%">
<thead>
<tr>
<th>Stock</th>
<th>Rate</th>
</tr>
</thead>
#if($trades)
#foreach($trades as $trade)
<tbody>
<tr>
<td>{{$trade->stock}}</td>
<td>{{$trade->rate}}</td>
</tr>
</tbody>
#endforeach
#endif
</table>
I worked hard but unable to find what i have not done.
I think you need to move your #foreach to be inside of your <tbody> like this:
<tbody>
#foreach($trades as $trade)
<tr>
<td>{{$trade->stock}}</td>
<td>{{$trade->rate}}</td>
</tr>
#endforeach
</tbody>
To get the sorting to work, you'll have to add an option to your javascript like this:
$(document).ready(function() {
$('#table').DataTable( {
"order": [[ 3, "desc" ]]
} );
} );
Which will order your table by the 4th column (since the 3 in the above example starts counting indexes at 0) in descending order. Reference - https://datatables.net/examples/basic_init/table_sorting.html

jQuery Datatables scroll to bottom when a row is added

I'd like my DataTable to scroll to the bottom whenever a row is added. I have tried multiple fixes for this problem, but none of them work.
Tested solutions:
How to load table in Datatables and have it scroll to last record automatically on load
Jquery DataTable auto scroll to bottom on load
Among others...
I think that what separates my case from the others, is that I am using DataTable with the D capitalized.
Anyway, here is my current code:
var table = $('#example').DataTable({
"createdRow": function( row, data, dataIndex )
{
$(row).attr('id', 'row-' + dataIndex);
},
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"scrollY": $(window).height()/1.5,
"scrollCollapse": true,
"paging": false,
});
for(var i = 1; i <= 20; i++){
table.row.add([
i,
'action'+i,
]);
}
table.draw();
table.rowReordering();
It would be nice if the table scrolled to bottom whenever a new row is added to it..
SOLUTION
To scroll to the bottom of the table, use the code below:
var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
DEMO
$(document).ready( function () {
var table = $('#example').DataTable({
"createdRow": function( row, data, dataIndex ) {
$(row).attr('id', 'row-' + dataIndex);
console.log($(row).closest('table').parent());
},
"scrollY": $(window).height()/1.5,
"scrollCollapse": true,
"paging": false
});
$('#btn-add').click(function(){
for(var i = 1; i <= 10; i++){
table.row.add([
i,
i + '.2',
i + '.3',
i + '.4',
i + '.5',
i + '.6'
]);
}
table.draw();
// Scroll to the bottom
var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
});
table.rowReordering();
} );
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>jQuery DataTables</title>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/mpryvkin/jquery-datatables-row-reordering/95b44786cb41cf37bd3ad39e39e1d216277bd727/media/js/jquery.dataTables.rowReordering.js"></script>
</head>
<body>
<button id="btn-add" type="button">Add records</button>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</body>
</html>

datatables select first row onload

I'm trying to auto select first row of table when data is loaded for the first time and failing to do that.
How do I auto select first row of table when table loads for the first time?
This html doesn't work:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css" title="currentStyle">
#import "DataTables/css/demo_page.css";
#import "DataTables/css/demo_table.css";
</style>
<script type="text/javascript" src="Datatables/js/jquery.js"></script>
<script type="text/javascript" src="Datatables/js/jquery.dataTables.js"></script>
<script>
var oTable;
var firstTime = true;
$(document).ready(function () {
$("#example tbody").click(function (event) {
$(oTable.fnSettings().aoData).each(function () {
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
oTable = $('#example').dataTable({
"sScrollX": "500px",
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "services/data3.ashx",
"sServerMethod": "POST",
"fnDrawCallback": function (oSettings) {
if (firstTime) {
alert('DataTables has redrawn the table');
oTable.$('tr:first').click();
firstTime = false;
}
}
});
});
</script>
</head>
<body>
<table border="1" >
<tr><td>id</td><td><input type="text" /></td></tr>
<tr><td>name</td><td><input type="text" /></td></tr>
<tr><td>surname</td><td><input type="text" /></td></tr>
</table><br />
<table id="example" border="1" class="display">
<thead>
<tr>
<td>name</td>
<td>surname</td>
<td>id</td>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>
oTable.$('tr:first') will raise an error - $ is not a function or property of oTable.
You must use
oTable.find('tbody tr:first').focus()
because tr:first will return the <thead> <tr>, not the <tbody> <tr>!
I dont think you by default can focus an entire <tr> in HTML, so you must add some CSS to the <tr> to make the focus visible. Like this
tr {
border:1px inset white;
}
tr.focused {
border:1px solid red;
}
oTable.find('tbody tr:first').addClass('focused');
An example of focusing rows when they are clicked :
oTable.find('tbody tr').click(function() {
oTable.find('tbody tr').removeClass('focused');
$(this).addClass('focused');
});
All the above in this fiddle -> http://jsfiddle.net/vv7Sa/
Check this link, it should help: https://www.datatables.net/forums/discussion/18305/select-first-row-onload. or you can try this:
$('#table-id').on('init.dt', function() {
$('#table-id tbody tr:eq(0)').click();
});

Categories