Javascript Datatables: remove unwanted horizontal scrolling - javascript

I'm using DataTables to display my data. I specify its width to be 4 bootstrap columns. My table now has this unwanted horizontal scroll at the bottom although all data can fit in the specified width:
Scrolling to the right, I see that the search box at the top is the reason for this scrolling:
What makes the box lie too far right? How do I fix this?
$(document).ready(function () {
var data = [
{ title: "The Godfather"},
{ title: "The Shawshank Redemption"},
{ title: "The Lord of the Rings: The Return of the King"},
{ title: "The Godfather: Part II"},
{ title: "Shichinin no samurai"},
{ title: "Buono, il brutto, il cattivo, Il"},
{ title: "Casablanca"},
{ title: "The Lord of the Rings: The Fellowship of the Ring"},
{ title: "The Lord of the Rings: The Two Towers"},
{ title: "Pulp Fiction"}
];
var table = d3.select("#myTable");
var rows = table
.select('tbody')
.selectAll('tr')
.data(data)
.enter()
.append('tr');
var cells = rows
.selectAll('td')
.data(function (data_row) {
return [data_row['title']];
})
.enter()
.append('td')
.text(function (d) {
return d;
});
$('#myTable').DataTable({
scrollY: '60vh',
paging : false,
});
});
body {
padding-top: 1%;
padding-bottom: 1%;
background: #585858 !important;
color: white;
}
<!DOCTYPE html>
<head>
<title>Data Tabke</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome lib -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css">
<!-- bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- dataTable -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<div class="row">
<div id="FilterableTable" class="col-4">
<div class="table-responsive">
<table class="table table-striped table-dark table-hover table-fit" id="myTable">
<thead class='thead-dark'>
<tr>
<th>My data</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div id="FilterableTable2" class="col-8">
<div class="table-responsive">
<table class="table table-striped table-dark table-hover table-fit" id="otherTable">
<thead class='thead-dark'>
<tr>
<th>Col 1</th>
<th>Col 2</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous"></script>
<!-- Popper.js -->
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<!-- dataTable -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<!-- D3 -->
<script src="https://d3js.org/d3.v3.min.js"></script>
</body>
UPDATE with snippet.

I have found a way to resolve this using DOM positioning of DataTables itself. I need to specify the structure of the table as <f>ti when initializing the table:
$('#myTable').DataTable({
scrollY: '60vh',
paging : false,
dom : "<f>ti"
});
and then style the searchbox to float left as:
#myTable_filter {
float: left !important;
}
The id myTable_filter is autogenerated by DataTables, so I need to check the correct ID of the element in Chrome.
Explanation of the <f>ti bit:
First, wrap the search box (the f element, or Filtering, according to DataTables documentation) in a div with < and >.
Put it before the table, or the t element.
The information element (the i) comes last. This is the info line that says "Showing 1 to x of x entries"

$(document).ready(function() {
var data = [{
title: "The Godfather"
},
{
title: "The Shawshank Redemption"
},
{
title: "The Lord of the Rings: The Return of the King"
},
{
title: "The Godfather: Part II"
},
{
title: "Shichinin no samurai"
},
{
title: "Buono, il brutto, il cattivo, Il"
},
{
title: "Casablanca"
},
{
title: "The Lord of the Rings: The Fellowship of the Ring"
},
{
title: "The Lord of the Rings: The Two Towers"
},
{
title: "Pulp Fiction"
}
];
var table = d3.select("#myTable");
var rows = table
.select('tbody')
.selectAll('tr')
.data(data)
.enter()
.append('tr');
var cells = rows
.selectAll('td')
.data(function(data_row) {
return [data_row['title']];
})
.enter()
.append('td')
.text(function(d) {
return d;
});
$('#myTable').DataTable({
scrollY: '60vh',
paging: false,
});
});
body {
padding-top: 1%;
padding-bottom: 1%;
background: #585858 !important;
color: white;
}
#myTable_info {
white-space: normal;
}
.dataTables_wrapper .row:first-child div:first-child {
width: 0;
max-width: 0;
padding: 0;
}
.dataTables_wrapper .row:first-child div:nth-child(2) {
min-width: 100%;
padding:0;
}
div.dataTables_wrapper div.dataTables_filter input {
width: calc(100% - 58px) !important;
max-width: 320px;
}
#myTable_filter {
min-width: 100%;
}
.dataTables_wrapper .row:nth-child(3) div:nth-child(1) {
min-width: 100%
}
<!DOCTYPE html>
<head>
<title>Data Tabke</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome lib -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css">
<!-- bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- dataTable -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<div class="row">
<div id="FilterableTable" class="col-4">
<div class="table-responsive">
<table class="table table-striped table-dark table-hover table-fit" id="myTable">
<thead class='thead-dark'>
<tr>
<th>My data</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div id="FilterableTable2" class="col-8">
<div class="table-responsive">
<table class="table table-striped table-dark table-hover table-fit" id="otherTable">
<thead class='thead-dark'>
<tr>
<th>Col 1</th>
<th>Col 2</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<!-- Popper.js -->
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<!-- dataTable -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<!-- D3 -->
<script src="https://d3js.org/d3.v3.min.js"></script>
</body>

Related

How to add Datatables plugin to dynamic json table code?

i m not able to make the following table dynamic using datatables plugin. here I am fetching json data using api and dynamically adding it to html table. i am not able to add datatables plugin and make it to work
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Covid tracker</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
</head>
<body>
<div class="table-responsive container">
<table class="table table-bordered table-hover ">
<thead class="table-dark">
<tr>
<th scope="col">Country</th>
<th scope="col">TotalConfirmed</th>
<th scope="col">TotalDeaths</th>
<th scope="col">TotalRecovered</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</body>
<script>
tbody = document.getElementById("tbody");
text = "";
data();
async function data() {
api = await fetch("https://api.covid19api.com/summary");
result = await api.json();
populate(result);
}
function populate(data) {
for (let x of data.Countries) {
text += ` <tr><td class="table-warning">${x.Country}</td><td class="table-danger">${x.TotalConfirmed}</td><td class="table-success">${x.TotalDeaths}</td><td class="table-primary">${x.TotalRecovered}</td></tr > `;
tbody.innerHTML = text;
}
}
</script>
</html>
The URL you are using already returns data as JSON:
{
"ID": "028dd159-922a-41cf-a768-892259b0adab",
"Message": "",
"Global": {
"NewConfirmed": 307033,
"TotalConfirmed": 171061979,
"NewDeaths": 12153,
"TotalDeaths": 3562587,
"NewRecovered": 428741,
"TotalRecovered": 108837399,
"Date": "2021-06-02T14:23:45.417Z"
},
"Countries": [
{
"ID": "35c3910f-e19a-48b4-afba-549e22cd4aac",
"Country": "Afghanistan",
"CountryCode": "AF",
"Slug": "afghanistan",
"NewConfirmed": 0,
"TotalConfirmed": 72977,
"NewDeaths": 0,
"TotalDeaths": 2973,
"NewRecovered": 0,
"TotalRecovered": 57741,
"Date": "2021-06-02T14:23:45.417Z",
"Premium": {}
},
...
],
"Date": "2021-06-02T14:23:45.417Z"
}
DataTables handles JSON out-of-the-box, so there is no need for any additional handler logic.
Your HTML table should be given an ID, so that DataTables can refer to it:
<table id="example" ...>
Your resource references in the page header appear to be completely missing what you need to support DataTables. You can go to the official download page, and select the ones you want to use.
Your page is missing the DataTables object, which points to the HTML table you want to use:
$('#example').DataTable( {...} );
Here is an example:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": {
"url": "https://api.covid19api.com/summary",
"dataSrc": "Countries"
},
"columns": [
{ data: "Country", className: 'table-warning' },
{ data: "TotalConfirmed", className: 'table-danger' },
{ data: "TotalDeaths", className: 'table-success' },
{ data: "TotalRecovered", className: 'table-primary' }
]
} );
} );
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Covid tracker</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/dataTables.bootstrap4.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<div class="table-responsive container">
<table id="example" class="table table-bordered table-hover ">
<thead class="table-dark">
<tr>
<th scope="col">Country</th>
<th scope="col">TotalConfirmed</th>
<th scope="col">TotalDeaths</th>
<th scope="col">TotalRecovered</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</body>
</html>
Beyond that, you can explore the many examples on the official web site.

How to add dropdown checkboxes in a jQuery table?

I have created a website mainly using HTML, CSS, PHP and MYSQL. I have successfully gotten tabledit working on the site, but I am not sure how to add the functionality for dropdown checkboxes. I need it to show as checked if the user has the role and when unchecked to update the MySQL table. Are dropdown checkboxes something that can be implemented with this plugin?
This is how the HTML is set up:
ModifyUser.php
<html>
<head>
<title>Modifying Users</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://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" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
<style>
#sample_data tr > *:nth-child(1) {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h3 align="center">Modifying Users</h3>
<br />
<div class="panel panel-default">
<!-- <div class="panel-heading">Sample Data</div>-->
<div class="panel-body">
<div class="table-responsive">
<table id="sample_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Approval</th>
<th>Roles</th> // COLUMN THAT SHOULD HAVE DROPDOWN CHECKBOX
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br />
<br />
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#sample_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"FetchUserTable.php",
type:"POST"
}
});
$('#sample_data').on('draw.dt', function(){
$('#sample_data').Tabledit({
url:'ActionUserTable.php',
dataType:'json',
columns:{
identifier : [0, 'user_id'],
editable:[
[1, 'first_name'],
[2, 'last_name'],
[3, 'email'],
[4, 'admin_approved', '{"1":"Approved","2":"Disapproved"}']
[5, 'role_id'] // THIS SHOULD BE AN EDITABLE DROPDOWN CHECKBOX
]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#' + data.id).remove();
$('#sample_data').DataTable().ajax.reload();
}
}
});
});
});
</script>

Appending chrome history to popup html and it keep flickering

I am trying to append chrome history URL, lastVisitTime, and Sno, everything work fine when URL is print as static text.
Problem arises when I print url's in table, it keep appending url, i don't understand this behaviour.
Here is popup.js
var count = 0;
var table = url = "";
var tbody = document.getElementById('tbody');
chrome.history.search({text: '', maxResults: 2}, function(data) {
data.forEach(function(page) {
count++;
url = page.url;
table += '<tr class="table-warning"><td scope="row">'+count+'</td><td>'+ url +'</td><td>'+page.lastVisitTime+'</td></tr>';
console.log('url', url);
});
tbody.innerHTML += table;
});
popup.html
<!DOCTYPE html>
<html>
<head>
<title>History tracker</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Sno</th>
<th scope="col">Website</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</div>
<script src="popup.js"></script>
</body>
</html>
After checking and wasting much time with it, I have found it was an CSS issue,
The container class was creating the problem so I removed the container class. It was width issue, the width of popup was not enough to show urls, so I removed time column and provide fixed width to URL column.
<!DOCTYPE html>
<html>
<head>
<title>History tracker</title>
<link rel="stylesheet" href="bootstrap.min.css">
<style>
table{
overflow-x: scroll;
}
td#history_url {
max-width: 500px;
word-break: break-word;
min-width: 500px;
}
</style>
</head>
<body>
<div class="">
<div class="row">
<div class="col-md-12">
<table class="table table-hover responsive">
<thead>
<tr>
<th scope="col">Sno</th>
<th scope="col">Website</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</div>
<script src="popup.js"></script>
</body>
</html>

.Datatable is not a function

I try this table feature
https://datatables.net/examples/basic_init/scroll_xy.html
i have dropdown and date picker so i add links for table and datetime picker links then i add table and also i use script for this but when i select datetime picker then calendar is not display then when i check console this show error
I try to export table data in excel
WebForm1.aspx:34 Uncaught TypeError: $(...).Datatable is not a function
CODE
<%--for tabledata--%>
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.3.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<link href="Styles/stylechart.css" rel="stylesheet" />
<!--for date--%>-->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tabledata").Datatable({
dom: 'Bfrtip',
buttons: [
'excelHtml5'
]
});
});
</script>
<table id="tabledata" cellspacing="0" class="display nowrap inner_table">
</table>
updated:
success: function (result) {
var final = JSON.parse(result.d).response;
console.log(JSON.parse(result.d).response);
$("#tabledata").empty();
if (final.length > 0) {
$("#tabledata").append(
"<thead><tr><th>RegNo</th></tr></thead>");
for (var i = 0; i < final.length; i++) {
if (final[i] !== null) {
$("#tabledata").append("<tbody><tr><td>" +
final[i][0] + "</td> </tr></tbody>");
}
}
}
you are using multiple references of jquery file.Also order is more important for any plugin to work properly.
Also try to avoid writing protocol http or https before script reference , just add simple // and it will automatically detect on which protocol your app is working and load reference file according to it.
change your reference section to scripts like given below.
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<link href="Styles/stylechart.css" rel="stylesheet" />
<!--for date--%>-->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tabledata").Datatable({
dom: 'Bfrtip',
buttons: [
'excelHtml5'
]
});
});
</script>
<table id="tabledata" cellspacing="0" class="display nowrap inner_table">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
</tr>
</thead>
</table>
try this:
$('#tabledata').DataTable({
sDom: 'TC<"clear">lfrtip',
"iDisplayLength": 10,
"oTableTools": {
***add*** "sSwfPath": "//cdn.datatables.net/tabletools/2.2.0/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"copy",
"csv",
"xls",
{

jQuery addClass not working in Bootstrap table

I have a Bootstrap table somewhat like this:
<table id="myTable">
<tr>
<th data-field="name" data-formatter="nameFormatter"></th>
<th data-field="number" data-formatter="numberFormatter"></th>
<th class="newClass"></th>
</tr>
</table>
jQuery
$('#myTable').on('click-row.bs.table', function (e, row, $element) {
// $('.newClass').removeClass('newClass');
$('.newClass').addClass('shown') // <-- this doesn't seem to work
}
CSS
td.newClass {
background-image: url("../../Content/Images/open.png");
}
tr.shown td.newClass {
background-image: url("../../Content/Images/close.png");
}
I am trying to addClass() on the row click event of the table but it doesn't seem to work. Am I missing something or doing something incorrectly.
It appears that your CSS does not match your markup:
tr.shown td.newClass
{
background-image: url("../../Content/Images/close.png");
}
Which is looking for the shown class on the table-row. But it looks like you are adding the shown class to the table-cell:
$('#myTable').on('click-row.bs.table', function (e, row, $element) {
//$('.newClass').removeClass('newClass');
$('.newClass').addClass('shown') // isn't $('.newClass') the cell and not the row?
}
UPDATE:
To fix this you can change your CSS:
td.newClass.shown { ... }
or your jQuery:
$element.addClass('shown');
It will help you :
$(document).ready(function(){
$("#myTable tr").on('click',function(){
$(this).find(".newClass").addClass("shown");
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8" />
<title>SPLessons</title>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body >
<div class="container">
<div class="jumbotron">
<h3>
SPLessons.com
</h3>
<table id="myTable" class="table table-bordered">
<tr>
<th data-field="name" data-formatter="nameFormatter"></th>
<th data-field="number" data-formatter="numberFormatter"></th>
<th class="newClass"></th>
</tr>
</table>
</div>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>

Categories

Resources