如何将HTML单选框值转换为文本文件?测验生成器开发咨询
Hey there! Let's build that quiz generator you need—perfect for teachers to create multiple-choice quizzes and export the data as a text file for your team's program. I've put together a complete, user-friendly implementation below with all the features you mentioned:
Complete Quiz Generator Code
HTML Structure
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Quiz Generator</title> <style> .question-container { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 8px; } .option-group { margin: 10px 0; } button { margin: 5px; padding: 8px 16px; cursor: pointer; } .export-btn { background-color: #2ecc71; color: white; border: none; border-radius: 4px; font-size: 16px; } .remove-btn { background-color: #e74c3c; color: white; border: none; border-radius: 4px; } </style> </head> <body> <h1>Quiz Generator</h1> <button onclick="addQuestion()">Add New Question</button> <div id="questions-container"> <!-- Questions will be added here dynamically --> </div> <br> <button class="export-btn" onclick="exportQuiz()">Export Quiz to Text File</button> <script> // Initialize with one question by default window.onload = function() { addQuestion(); }; // Add a new question block function addQuestion() { const container = document.getElementById('questions-container'); const questionId = `question-${container.children.length + 1}`; const questionBlock = document.createElement('div'); questionBlock.className = 'question-container'; questionBlock.innerHTML = ` <h3>Question ${container.children.length + 1}</h3> <input type="text" id="${questionId}-text" placeholder="Enter question text here..." required> <div class="option-group"> <label> <input type="radio" name="${questionId}-correct" value="option1" required> <input type="text" id="${questionId}-option1" placeholder="Option 1..." required> </label> </div> <div class="option-group"> <label> <input type="radio" name="${questionId}-correct" value="option2"> <input type="text" id="${questionId}-option2" placeholder="Option 2..." required> </label> </div> <div class="option-group"> <label> <input type="radio" name="${questionId}-correct" value="option3"> <input type="text" id="${questionId}-option3" placeholder="Option 3..." required> </label> </div> <div class="option-group"> <label> <input type="radio" name="${questionId}-correct" value="option4"> <input type="text" id="${questionId}-option4" placeholder="Option 4..." required> </label> </div> <button class="remove-btn" onclick="removeQuestion(this)">Remove Question</button> `; container.appendChild(questionBlock); } // Remove a question block function removeQuestion(btn) { const container = document.getElementById('questions-container'); // Don't let the user remove the last question if (container.children.length > 1) { btn.parentElement.remove(); // Re-number questions after removal updateQuestionNumbers(); } else { alert("You need at least one question in the quiz!"); } } // Update question numbers when one is removed function updateQuestionNumbers() { const questions = document.querySelectorAll('.question-container'); questions.forEach((q, index) => { q.querySelector('h3').textContent = `Question ${index + 1}`; const questionId = `question-${index + 1}`; q.querySelector(`input[id$="-text"]`).id = `${questionId}-text`; const radioInputs = q.querySelectorAll(`input[type="radio"]`); radioInputs.forEach(radio => { radio.name = `${questionId}-correct`; }); // Update option IDs too for (let i = 1; i <=4; i++) { q.querySelector(`input[id$="-option${i}"]`).id = `${questionId}-option${i}`; } }); } // Export quiz data to text file function exportQuiz() { const quizData = []; const questions = document.querySelectorAll('.question-container'); // Validate all inputs first let isValid = true; questions.forEach(q => { const questionText = q.querySelector('input[id$="-text"]').value.trim(); const option1 = q.querySelector('input[id$="-option1"]').value.trim(); const option2 = q.querySelector('input[id$="-option2"]').value.trim(); const option3 = q.querySelector('input[id$="-option3"]').value.trim(); const option4 = q.querySelector('input[id$="-option4"]').value.trim(); const correctOption = q.querySelector(`input[type="radio"]:checked`); if (!questionText || !option1 || !option2 || !option3 || !option4 || !correctOption) { isValid = false; alert(`Please fill out all fields for Question ${Array.from(questions).indexOf(q)+1}!`); } else { // Build question object const correctValue = q.querySelector(`input[id$="-${correctOption.value}"]`).value.trim(); quizData.push({ question: questionText, options: [option1, option2, option3, option4], correctAnswer: correctValue }); } }); if (!isValid) return; // Convert to JSON format (easy for your team to parse) const textContent = JSON.stringify(quizData, null, 2); // Create and download the text file const blob = new Blob([textContent], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'quiz-data.txt'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); alert('Quiz exported successfully! Check your downloads folder.'); } </script> </body> </html>
Key Features Explained
- Dynamic Question Management: Teachers can add as many questions as needed, and remove any except the last one (to avoid empty quizzes). Questions auto-renumber when removed.
- Validation: Ensures all fields are filled out and a correct answer is selected before export—no incomplete data makes it to the text file.
- Clean Export Format: The exported text file uses JSON (human-readable and easy to parse) with each question containing:
- The question text
- An array of 4 options
- The exact text of the correct answer
- User-Friendly UI: Simple styling to make input easy, with clear buttons for adding/removing questions and exporting.
Customization Tips
If your team needs a different text format (instead of JSON), you can modify the exportQuiz function. For example, to use a delimiter-separated format:
// Example delimiter format (change as needed) let textContent = ''; quizData.forEach((q, index) => { textContent += `Question ${index+1}: ${q.question}\n`; textContent += `Options:\n- ${q.options[0]}\n- ${q.options[1]}\n- ${q.options[2]}\n- ${q.options[3]}\n`; textContent += `Correct Answer: ${q.correctAnswer}\n\n`; });
Just swap that in place of the JSON stringify line, and the export will be in a plain-text, human-readable format instead.
内容的提问来源于stack exchange,提问作者skaiyly
相关产品推荐
相关产品推荐

