Как редактировать несколько файлов в jQueryCSS

Разбираемся в CSS
Ответить
Anonymous
 Как редактировать несколько файлов в jQuery

Сообщение Anonymous »

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

Код: Выделить всё

$('#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(`
[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 => `

[url=${link.trim()}]${link.substring(link.lastIndexOf('/') + 1)}[/url]
[/i]

`).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 => `

[url=${link.trim()}]${link.substring(link.lastIndexOf('/') + 1)}[/url]

[i][/i]


`).join('');

// Update the lab report section with both existing and new links
$(this).closest('tr').find('.labReport').html(`

${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.');
}
});
});
});



Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-jquery
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «CSS»