На самом деле у меня возникла проблема с функцией редактирования при нажатии кнопки редактирования. Я включил поля соответствующей строки, и у меня есть столбец лабораторного отчета. Я показываю несколько файлов в этом столбце, поэтому, когда я нажимаю «Редактировать», я активирую поле ввода для загрузки файлов, а также сохраняю существующий файл, но когда я нажимаю кнопку «Редактировать», появляется поле ввода (загрузка файла) и существующие файлы несколько раз. Например, если у меня есть 3 файла, это будет выглядеть так:
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
А если у меня 4 файла, то оно придет четыре раза. В чем проблема? На самом деле, я хочу продемонстрировать это поле ввода и существующие файлы.
Пожалуйста, помогите мне.
На самом деле у меня возникла проблема с функцией редактирования при нажатии кнопки редактирования. Я включил поля соответствующей строки, и у меня есть столбец лабораторного отчета. Я показываю несколько файлов в этом столбце, поэтому, когда я нажимаю «Редактировать», я активирую поле ввода для загрузки файлов, а также сохраняю существующий файл, но когда я нажимаю кнопку «Редактировать», появляется поле ввода (загрузка файла) и существующие файлы несколько раз. Например, если у меня есть 3 файла, это будет выглядеть так: [code]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 [/code] А если у меня 4 файла, то оно придет четыре раза. В чем проблема? На самом деле, я хочу продемонстрировать это поле ввода и существующие файлы. Пожалуйста, помогите мне.
// 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(` [i] `);
// 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 => `
`).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] || [];