I am initializing the datatable on file input. I choose a csv file, parse it and initialize the datatable with the parsed data. It works fine for the first time, but I choose another file afterwards, the datatable is not being initialized properly. I have tried destroying the table in case it already exists but I am still getting errors while re-initializing it.
var csv_data;
var file_name;
$("#input_file").change(function() {
if (this.files && this.files[0]) {
var file = this.files[0];
file_name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
csv_data = e.target.result;
// Parse CSV data to JavaScript objects
var parsedData = parseCSVtoObjects(csv_data);
console.log("Parsed Data : ", parsedData);
// Check if parsed data is not empty
if (parsedData.length > 0) {
if ($.fn.DataTable.isDataTable("#dataTable")) {
$("#dataTable").DataTable().destroy();
$("#dataTable tbody").empty();
}
// Re-initialize DataTable with new data
initializeDataTable(parsedData);
}
};
reader.readAsText(file); // Reading the file content as text
}
});
function parseCSVtoObjects(csvData) {
var lines = csvData.split("n").filter(line => line.trim() !== "");
if (
lines.length < 2) return []; // Ensure there's at least one row of data
var headers = ["Line Number"].concat(lines[0].split(","));
var result = [];
for (var i = 0; i < lines.length; i++) {
var obj = {
"Line Number": i
};
var currentLine = lines[i].split(",");
if (currentLine.length !== headers.length - 1) {
console.warn(`Skipping line ${i}: does not match the number of headers.`);
continue;
}
headers.slice(1).forEach((header, index) => {
obj[header.trim()] = currentLine[index].trim();
});
result.push(obj);
}
return result;
}
function initializeDataTable(data) {
// Get headers from the first row of data
headers = Object.keys(data[0]);
// Build column definitions dynamically
const columns = headers.map(header => ({
"data": header,
"title": header
}));
var first10Records = data;
if (data.length > 10) {
first10Records = data.slice(0, 11);
}
$("#dataTable").DataTable({
"data": first10Records,
"columns": columns,
"paging": false, // Disables pagination
"lengthChange": false, // Disables ability to change results number per page
"searching": false, // Disables the search box
"info": false, // Hides the table information
"ordering": false,
"bDestroy": true
});
$(".even").css("background-color", "#DCDBDB");
$("th, td").css("width", "100px");
var global_columns = [
["-1", "Not Used in Import"],
["date", "Date"],
["branch", "Branch"],
["start_time", "Start Time"],
["store_id", "Store ID"],
["end_time", "End Time"],
["rate", "Rate"],
["start_end_time", "Start End Time"],
["branch_with_store_id", "Branch With Store ID"]
];
// Function to create a filter select element
function createFilterSelect(id) {
var select = $("<select></select>", {
"id": id,
"class": "rs_normal_text w2ui-select w2ui-field w2ui-input",
"style": "width: 100%;"
});
global_columns.forEach(([value, text]) => {
select.append($("<option></option>", {
"value": value,
"text": text
}).clone());
});
return select;
}
filterPositions = [];
for (let i = 1; i <= headers.length - 1; i++) {
filterPositions.push(i);
}
// Append filters to specified cells
filterPositions.forEach((pos, index) => {
$(`#dataTable tbody tr:eq(0) td:eq(${pos})`).html(createFilterSelect(`grid_filter_${index + 1}`));
});
}
// Data table div start
var $tableDivHeading = $("<div>Import Shifts </div>").attr("id", "tableDivHeading");
$tableDivHeading.addClass("rs_listview_title").css({
"width": "100%",
"display": "flex",
"align-items": "center",
"justify-content": "center"
});
var $dataTableDiv = $("<div></div>").attr("id", "dataTableDiv");
var $dataTable = $("<table></table>").attr("id", "dataTable").css({
"height": "600px"
});
$("#container_grid").append($tableDivHeading);
$("#container_grid").append($dataTableDiv);
$("#dataTableDiv").append($dataTable);