I have this html table:
<main class="main-content">
<div class="row">
<div class="card col-12">
<div class="card-body">
<h6 class="my-3">Daily Dispense Report</h6>
<div class="my-3">
<label for="date">Select date</label>
<input type="month" id="date" class="form-control col-12 col-md-4">
</div>
<table class="table table-bordered" id="dailyDispenseTable">
<thead>
<tr>
<th>#</th>
<th style="min-width: 150px;">Medicine Name</th>
<th style="min-width: 150px;">Dosage</th>
</tr>
</thead>
<tbody id="dailyDispense"></tbody>
</table>
</div>
</div>
</div>
</main
Using DataTable jquery library, I want to add another 4th column dynamically. But this column should be many columns represinting days of the selected month. Right now, I’m able to do that for the current month (April) but the number of columns don’t update when the month changes (ex: Feb which has 29 days).
my api data
"data": [
{
"medicine_id": 2128,
"name": "Erythromycin Tab. 250 mg",
"dosage": null,
"month": "Feb",
"total_dispensed_qty": [
{
"day_0": 0
},
{
"day_2": 210
},
{
"day_3": 495
},
{
"day_4": 615
},
{
"day_5": 540
},
{
"day_6": 465
},
{
"day_7": 375
},
{
"day_8": 180
},
{
"day_9": 360
},
{
"day_10": 30
},
{
"day_11": 15
},
{
"day_12": 150
},
{
"day_13": 195
},
{
"day_14": 60
},
{
"day_15": 195
},
{
"day_16": 180
},
{
"day_17": 150
},
{
"day_0": 0
},
{
"day_0": 0
},
{
"day_20": 240
},
{
"day_21": 60
},
{
"day_22": 90
},
{
"day_23": 33
},
{
"day_24": 95
},
{
"day_25": 100
},
{
"day_26": 210
},
{
"day_27": 150
},
{
"day_0": 0
},
{
"day_29": 150
}
]
},
{
"medicine_id": 7352,
"name": "paracetamol 500mg",
"dosage": null,
"month": "Feb",
"total_dispensed_qty": [
{
"day_0": 0
},
{
"day_2": 213
},
{
"day_3": 339
},
{
"day_4": 294
},
{
"day_5": 228
},
{
"day_6": 270
},
{
"day_7": 154
},
{
"day_8": 246
},
{
"day_9": 408
},
{
"day_10": 27
},
{
"day_11": 312
},
{
"day_12": 259
},
{
"day_13": 246
},
{
"day_14": 84
},
{
"day_15": 144
},
{
"day_16": 199
},
{
"day_17": 192
},
{
"day_18": 93
},
{
"day_0": 0
},
{
"day_20": 190
},
{
"day_21": 156
},
{
"day_22": 165
},
{
"day_23": 90
},
{
"day_24": 213
},
{
"day_25": 153
},
{
"day_26": 90
},
{
"day_27": 90
},
{
"day_28": 51
},
{
"day_29": 138
}
]
},
]
Also with my below JavaScript code, the month-day (ex: Apr-1, Apr-2, etc.) get added to the body instead of the header section of the table.
JavaScript
$(function (){
const today = new Date();
// Get the current year and month components
const year = today.getFullYear();
const month = (today.getMonth() + 1).toString().padStart(2, '0');
const currentMonth = today.getMonth() + 1;
const lastDayOfMonth = new Date(today.getFullYear(), currentMonth, 0).getDate();
const defaultYearMonth = `${year}-${month}`;
function createPeriodCols(monthLength){
const [year, month] = monthLength.split('-').map(Number);
const nextMonthFirstDay = new Date(year, month - 1, 1);
const lastDay = new Date(year, month, 0);
const finalDate = lastDay.getDate();
for (let i = 1; i <= finalDate; i++) {
$('#dailyDispenseTable thead tr').append(
`<th class="month-date" style="min-width: 100px;"></th>`
);
}
}
$('#date').val(defaultYearMonth);
function getDayAndMonth(dateString) {
const [year, month] = dateString.split('-').map(Number);
const nextMonthFirstDay = new Date(year, month - 1, 1);
const lastDay = new Date(year, month, 0);
const finalDate = lastDay.getDate();
const monthNames = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];
const monthName = monthNames[nextMonthFirstDay.getMonth()];
// Update headers with new month and date information
for (let i = 1; i <= finalDate; i++) {
const columnIndex = i + 3;
$(`#dailyDispenseTable thead tr th:nth-child(${columnIndex})`).html(`${monthName}-${i}`);
}
}
// Fetch data and update table based on the selected date
function fetchDataAndUpdateTable(date) {
$.ajax({
url: `api/v1/daily-dispense?date=${date}`,
dataType: "json",
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", `BEARER ${localStorage.token}`)
},
success: function ({ data }, xhr) {
if (data) {
updateTable(data);
}
},
error: function (err) {
console.log(err);
},
});
}
// Fetch data for the default date on page load
let defaultDate = $('#date').val();
fetchDataAndUpdateTable(defaultDate);
createPeriodCols(defaultDate);
// Fetch data and update table when date is changed
$('#date').on('change', function () {
const selectedDate = $(this).val();
fetchDataAndUpdateTable(selectedDate);
});
const table = $("#dailyDispenseTable").DataTable({
fixedColumns: {
leftColumns: 3
},
paging: true,
search: true,
scrollX: true,
scrollY: 700,
initComplete: function(settings, json) {
},
drawCallback: function(settings){
const selectedDate = $('#date').val();
getDayAndMonth(selectedDate);
}
});
function updateTable(data) {
if (!data || data.length === 0) {
table.clear().draw();
return;
}
table.clear().draw(); // Clear existing data
const dailyMedicineQty = (item) => {
let values = [];
for(let day = 1; day <= lastDayOfMonth; day++){
let dayQty = item?.total_dispensed_qty?.find(qty => qty[`day_${day}`] !== undefined);
values.push(dayQty ? dayQty[`day_${day}`] : 0);
}
return values;
};
data.forEach((item, idx) => {
if (!item.dosage) item.dosage = '';
let dailyQty = dailyMedicineQty(item);
const rowData = [
idx + 1,
item?.name,
item?.dosage,
...dailyQty
];
table.row.add(rowData).draw(false);
table.processing(true)
});
}
});
The resources I’m using from from DataTable website based on my preferences in the Download section
JS: https://cdn.datatables.net/v/bs4/dt-2.0.5/fc-5.0.0/datatables.min.js
CSS: https://cdn.datatables.net/v/bs4/dt-2.0.5/fc-5.0.0/datatables.min.css