Actually, I am facing an issue with the edit functionality while hitting on the edit button. I have enabled the fields of the respective row and in that I have a lab-report column. I am showing multiple files in that column so when I hit on edit am enabled input field to upload the files and also holding existing file, but when I hit on the edit button it's coming input field (file upload) and existing files multiple times. For example, if I have 3 files, it's coming like this:
No file chosen
47.pdf
48.pdf
49.pdf
No file chosen
47.pdf
48.pdf
49.pdf
No file chosen
47.pdf
48.pdf
49.pdf
And if I have 4 files, it's coming four times. What is the issue? Actually, I want to showcase once that input field and existing files.
Please help me, anyone.
$('#addPackagingModuleList tbody').on('click', '.edit-btn', function () {
const $row = $(this).closest('tr');
const isEditing = $(this).text() === 'Update';
const rowId = $(this).data('id');
console.log('Entered inside the edit function');
// For handling when the edit button is clicked
if (isEditing) {
$(this).text('Edit');
$row.find('input, select').prop('disabled', true);
// Prepare updated data (this remains unchanged)
const variety = $row.find('.variety-select').val();
const otherVariety = $row.find('.other-variety-input').val();
const labReportLink = existingLabReports[rowId].concat(labReportUrls).join(','); // Combine existing and new URLs
const updatedData = {
id: rowId,
labReport: labReportLink,
farmSlide: "", // Fill with your desired link if needed
farmCertifications: "",
farmPackagingVideo: "",
growerName: $row.find('.grower-name').val(),
crop: $row.find('.crop').val(),
variety: variety === 'Other' ? otherVariety : variety,
farmRegistrationNumber: $row.find('.farm-registration-number').val(),
ggn: $row.find('.ggn').val(),
lotTracebility: $row.find('.lot-traceability').val(),
customerName: $row.find('.customerName').val(),
};
// Send updated data to the server
$.ajax({
url: '/admin/sys/sec/edit/qrcode/details',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(updatedData),
success: function (response) {
if (response.status) {
table.ajax.reload();
$('#alert-message').text(response.data);
$('#alert-container').show();
setTimeout(function () {
$('#alert-container').fadeOut();
}, 3000);
location.reload();
} else {
alert('Error updating data.');
}
},
error: function () {
alert('Failed to update data.');
}
});
} else {
// When the "Edit" button text is "Update"
$(this).text('Update');
$row.find('input, select').prop('disabled', false);
// Grab the lab report container
const $labReportContainer = $row.find('.labReport');
// Log the state of the lab report container before clearing it
console.log('Before clearing, labReportContainer:', $labReportContainer.html());
// Clear out any previous content in the labReport section
$labReportContainer.empty();
// Log again after clearing
console.log('After clearing, labReportContainer:', $labReportContainer.html());
// Add file input field (only once)
$labReportContainer.append(`
<input type="file" class="form-control labReportInput" accept="application/pdf">
`);
// Log the state of the lab report container after adding file input
console.log('After adding file input, labReportContainer:', $labReportContainer.html());
// Check if there are existing lab reports and append them
if (existingLabReports[rowId] && existingLabReports[rowId].length > 0) {
const existingReportsHtml = existingLabReports[rowId].map(link => `
<div class="existing-lab-report" data-url="${link.trim()}">
<a href="${link.trim()}" target="_blank">${link.substring(link.lastIndexOf('/') + 1)}</a>
<i type="button" class="remove-lab-report-btn fa fa-times" style="font-size: 14px; color: #dc3545;"></i>
</div>
`).join('');
$labReportContainer.append(existingReportsHtml); // Append the existing reports only once
}
// Final log after appending all content
console.log('Final state of labReportContainer:', $labReportContainer.html());
}
});
// Handle file input change for lab report
$('#addPackagingModuleList tbody').on('change', '.labReportInput', function () {
const labReportFiles = this.files;
// Loop through each file to validate and upload
Array.from(labReportFiles).forEach(file => {
if (file.size > MAX_FILE_SIZE) {
alert('File size exceeds the 1MB limit.');
return;
}
const formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/admin/sys/sec/qr/uploadFile',
type: 'POST',
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
if (response.status) {
// Store the uploaded file URL in the array
labReportUrls.push(response.data); // Store the new file URL
// Update the UI to display the new lab report next to the existing ones
const rowId = $(this).closest('tr').find('.edit-btn').data('id');
const existingReports = existingLabReports[rowId] || [];
// Combine existing and newly uploaded URLs
const allReports = [...existingReports, response.data];
// Create the new HTML for the lab report links
const labReportLinks = allReports.map(link => `
<div class="existing-lab-report" data-url="${link.trim()}">
<a href="${link.trim()}" target="_blank">${link.substring(link.lastIndexOf('/') + 1)}</a>
<button type="button" class="remove-lab-report-btn btn-sm btn-danger ms-1">
<i class="fa fa-times"></i>
</button>
</div>
`).join('');
// Update the lab report section with both existing and new links
$(this).closest('tr').find('.labReport').html(`
<input type="file" class="form-control labReportInput" accept="application/pdf">
${labReportLinks}
`);
// Optionally, display a success message
$('#alert-message').text(response.message);
$('#alert-container').removeClass('alert-danger').addClass('alert-success').show();
setTimeout(function () {
$('#alert-container').fadeOut();
}, 3000);
} else {
alert('Error uploading file.');
}
},
error: function () {
alert('Error uploading file. Please try again.');
}
});
});
});