это интерфейс моего Django. Короче говоря, вы выбираете класс и тему с параметрами, динамически заполняемыми из переменных контекста Django.
Затем, в зависимости от типа загрузки, должно появиться несколько строк загрузки, где каждая строка может иметь разные типы загрузки файлов в зависимости от типа загрузки. для выбранного типа.
Предполагается, что addUploadRow динамически добавляет новые строки загрузки в div-строки загрузки.
Однако строки не выскакивают.
Я новичок в JS и HTML. есть идеи, в чем проблема?
вот мой код
Assignment Upload
{% load static %}
Assignment Upload
Class:
Select Class
{% for class in classes %}
{{ class.identifier }} (Year {{ class.year }})
{% endfor %}
Subject:
Select Subject
{% for subject in subjects %}
{{ subject.name }}
{% endfor %}
Upload Type:
Select Upload Type
All in One
Separate Files
Combined Question Rubric, Separate Answer
Question and Answer
Students:
Please select at least one student.
Upload
Upload Progress:
0%
Add Upload
×
let uploadCounter = 1;
function addUploadRow() {
const uploadRowTemplate = `
Upload Type:
Select Upload Type
All in One
Separate Files
Combined Question Rubric, Separate Answer
Question and Answer
Students:
Please select at least one student.
Upload
Upload Progress:
0%
`;
const uploadRows = document.getElementById('upload-rows');
uploadRows.insertAdjacentHTML('beforeend', uploadRowTemplate);
uploadCounter++;
}
function toggleFileInputs(selectElement, index) {
const uploadType = selectElement.value;
const fileInputSection = document.getElementById(`file-input-section-${index}`);
fileInputSection.innerHTML = ''; // Clear previous file inputs
if (uploadType === 'all_in_one') {
fileInputSection.innerHTML = `
Upload All in One File:
`;
} else if (uploadType === 'separate_files') {
fileInputSection.innerHTML = `
Upload Question File:
Upload Answer File:
Upload Rubric File:
`;
} else if (uploadType === 'qr_combined_a_separate') {
fileInputSection.innerHTML = `
Upload Combined Question and Rubric File:
Upload Answer File:
`;
} else if (uploadType === 'question_answer') {
fileInputSection.innerHTML = `
Upload Question and Answer File:
`;
}
}
function uploadFiles(button) {
const uploadRow = button.closest('.upload-row');
const formData = new FormData();
// Append the file inputs to the FormData object
const fileInputs = uploadRow.querySelectorAll('input[type="file"]');
fileInputs.forEach((input) => {
if (input.files[0]) {
formData.append(input.name, input.files[0]);
}
});
// Append the select inputs to the FormData object
const selectInputs = uploadRow.querySelectorAll('select');
selectInputs.forEach((input) => {
formData.append(input.name, input.value);
});
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/', true);
const progressBarContainer = uploadRow.querySelector('[id^="progress-bar-container"]');
const progressBar = uploadRow.querySelector('[id^="progress-bar"]');
const progressBarPercentage = uploadRow.querySelector('[id^="progress-bar-percentage"]');
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
progressBar.style.width = percentComplete + '%';
progressBarPercentage.innerText = Math.round(percentComplete) + '%';
}
};
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
document.getElementById('upload-success-message').innerText = response.message;
document.getElementById('upload-success-modal').classList.remove('hidden');
} else {
console.error('Upload failed.');
}
};
xhr.send(formData);
progressBarContainer.classList.remove('hidden');
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('class_id').addEventListener('change', function() {
const classId = this.value;
const studentSelects = document.querySelectorAll('select[id^="student_ids_"]');
if (classId) {
fetch(`/get-students-for-class/${classId}/`)
.then(response => response.json())
.then(data => {
studentSelects.forEach(select => {
select.innerHTML = ''; // Clear existing options
data.students.forEach(student => {
const option = new Option(student.name, student.id);
select.add(option);
});
});
})
.catch(error => console.error('Error fetching students:', error));
} else {
studentSelects.forEach(select => select.innerHTML = ''); // Clear if no class is selected
}
});
// Ensure toggleFileInputs works for the initial row
document.getElementById('upload_type_0').addEventListener('change', function() {
toggleFileInputs(this, 0);
});
});
Я создал единственную функцию, которая динамически добавляет строки, но не могу интегрировать ее в основной код:
Assignment Upload
Assignment Upload
Add Upload
document.addEventListener('DOMContentLoaded', function() {
// Function to add a new upload row
document.getElementById('addUploadRow').addEventListener('click', function() {
const uploadRows = document.getElementById('upload-rows');
const index = uploadRows.children.length;
const newRow = document.createElement('div');
newRow.className = 'upload-row grid grid-cols-1 gap-4 md:grid-cols-2 p-4 bg-white shadow rounded';
newRow.innerHTML = `
Upload Type:
Select Upload Type
All in One
Separate Files
Combined Question Rubric, Separate Answer
Question and Answer
`;
uploadRows.appendChild(newRow);
// Add change listener to new select element
document.getElementById(`upload_type_${index}`).addEventListener('change', function() {
toggleFileInputs(this, index);
});
});
// Function to toggle file inputs based on selected upload type
function toggleFileInputs(selectElement, index) {
const uploadType = selectElement.value;
const fileInputSection = document.getElementById(`file-input-section-${index}`);
fileInputSection.innerHTML = ''; // Clear existing inputs
if (uploadType === 'all_in_one') {
fileInputSection.innerHTML = `
Upload All in One File:
`;
} else if (uploadType === 'separate_files') {
fileInputSection.innerHTML = `
Upload Question File:
Upload Answer File:
Upload Rubric File:
`;
} else if (uploadType === 'qr_combined_a_separate') {
fileInputSection.innerHTML = `
Upload Combined Question and Rubric File:
Upload Answer File:
`;
} else if (uploadType === 'question_answer') {
fileInputSection.innerHTML = `
Upload Question and Answer File:
`;
}
}
// Trigger the first row addition on load
document.getElementById('addUploadRow').click();
});
Подробнее здесь: https://stackoverflow.com/questions/786 ... pload-rows
Динамически добавлять новые строки загрузки ⇐ CSS
Разбираемся в CSS
-
Anonymous
1719227984
Anonymous
это интерфейс моего Django. Короче говоря, вы выбираете класс и тему с параметрами, динамически заполняемыми из переменных контекста Django.
Затем, в зависимости от типа загрузки, должно появиться несколько строк загрузки, где каждая строка может иметь разные типы загрузки файлов в зависимости от типа загрузки. для выбранного типа.
Предполагается, что addUploadRow динамически добавляет новые строки загрузки в div-строки загрузки.
Однако строки не выскакивают.
Я новичок в JS и HTML. есть идеи, в чем проблема?
вот мой код
Assignment Upload
{% load static %}
Assignment Upload
Class:
Select Class
{% for class in classes %}
{{ class.identifier }} (Year {{ class.year }})
{% endfor %}
Subject:
Select Subject
{% for subject in subjects %}
{{ subject.name }}
{% endfor %}
Upload Type:
Select Upload Type
All in One
Separate Files
Combined Question Rubric, Separate Answer
Question and Answer
Students:
Please select at least one student.
Upload
Upload Progress:
0%
Add Upload
×
let uploadCounter = 1;
function addUploadRow() {
const uploadRowTemplate = `
Upload Type:
Select Upload Type
All in One
Separate Files
Combined Question Rubric, Separate Answer
Question and Answer
Students:
Please select at least one student.
Upload
Upload Progress:
0%
`;
const uploadRows = document.getElementById('upload-rows');
uploadRows.insertAdjacentHTML('beforeend', uploadRowTemplate);
uploadCounter++;
}
function toggleFileInputs(selectElement, index) {
const uploadType = selectElement.value;
const fileInputSection = document.getElementById(`file-input-section-${index}`);
fileInputSection.innerHTML = ''; // Clear previous file inputs
if (uploadType === 'all_in_one') {
fileInputSection.innerHTML = `
Upload All in One File:
`;
} else if (uploadType === 'separate_files') {
fileInputSection.innerHTML = `
Upload Question File:
Upload Answer File:
Upload Rubric File:
`;
} else if (uploadType === 'qr_combined_a_separate') {
fileInputSection.innerHTML = `
Upload Combined Question and Rubric File:
Upload Answer File:
`;
} else if (uploadType === 'question_answer') {
fileInputSection.innerHTML = `
Upload Question and Answer File:
`;
}
}
function uploadFiles(button) {
const uploadRow = button.closest('.upload-row');
const formData = new FormData();
// Append the file inputs to the FormData object
const fileInputs = uploadRow.querySelectorAll('input[type="file"]');
fileInputs.forEach((input) => {
if (input.files[0]) {
formData.append(input.name, input.files[0]);
}
});
// Append the select inputs to the FormData object
const selectInputs = uploadRow.querySelectorAll('select');
selectInputs.forEach((input) => {
formData.append(input.name, input.value);
});
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/', true);
const progressBarContainer = uploadRow.querySelector('[id^="progress-bar-container"]');
const progressBar = uploadRow.querySelector('[id^="progress-bar"]');
const progressBarPercentage = uploadRow.querySelector('[id^="progress-bar-percentage"]');
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
progressBar.style.width = percentComplete + '%';
progressBarPercentage.innerText = Math.round(percentComplete) + '%';
}
};
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
document.getElementById('upload-success-message').innerText = response.message;
document.getElementById('upload-success-modal').classList.remove('hidden');
} else {
console.error('Upload failed.');
}
};
xhr.send(formData);
progressBarContainer.classList.remove('hidden');
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('class_id').addEventListener('change', function() {
const classId = this.value;
const studentSelects = document.querySelectorAll('select[id^="student_ids_"]');
if (classId) {
fetch(`/get-students-for-class/${classId}/`)
.then(response => response.json())
.then(data => {
studentSelects.forEach(select => {
select.innerHTML = ''; // Clear existing options
data.students.forEach(student => {
const option = new Option(student.name, student.id);
select.add(option);
});
});
})
.catch(error => console.error('Error fetching students:', error));
} else {
studentSelects.forEach(select => select.innerHTML = ''); // Clear if no class is selected
}
});
// Ensure toggleFileInputs works for the initial row
document.getElementById('upload_type_0').addEventListener('change', function() {
toggleFileInputs(this, 0);
});
});
Я создал единственную функцию, которая динамически добавляет строки, но не могу интегрировать ее в основной код:
Assignment Upload
Assignment Upload
Add Upload
document.addEventListener('DOMContentLoaded', function() {
// Function to add a new upload row
document.getElementById('addUploadRow').addEventListener('click', function() {
const uploadRows = document.getElementById('upload-rows');
const index = uploadRows.children.length;
const newRow = document.createElement('div');
newRow.className = 'upload-row grid grid-cols-1 gap-4 md:grid-cols-2 p-4 bg-white shadow rounded';
newRow.innerHTML = `
Upload Type:
Select Upload Type
All in One
Separate Files
Combined Question Rubric, Separate Answer
Question and Answer
`;
uploadRows.appendChild(newRow);
// Add change listener to new select element
document.getElementById(`upload_type_${index}`).addEventListener('change', function() {
toggleFileInputs(this, index);
});
});
// Function to toggle file inputs based on selected upload type
function toggleFileInputs(selectElement, index) {
const uploadType = selectElement.value;
const fileInputSection = document.getElementById(`file-input-section-${index}`);
fileInputSection.innerHTML = ''; // Clear existing inputs
if (uploadType === 'all_in_one') {
fileInputSection.innerHTML = `
Upload All in One File:
`;
} else if (uploadType === 'separate_files') {
fileInputSection.innerHTML = `
Upload Question File:
Upload Answer File:
Upload Rubric File:
`;
} else if (uploadType === 'qr_combined_a_separate') {
fileInputSection.innerHTML = `
Upload Combined Question and Rubric File:
Upload Answer File:
`;
} else if (uploadType === 'question_answer') {
fileInputSection.innerHTML = `
Upload Question and Answer File:
`;
}
}
// Trigger the first row addition on load
document.getElementById('addUploadRow').click();
});
Подробнее здесь: [url]https://stackoverflow.com/questions/78662096/dynamically-add-new-upload-rows[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия