如何用JavaScript实现表单提交时生成用户输入的奖牌数据表格及柱状图
Solution: Form to Dynamic Bar Chart for Champions League Medals
Alright, let's build this from scratch. I'll provide a complete, self-contained implementation using vanilla HTML, CSS, and JavaScript—no external libraries needed, so it's easy to integrate anywhere.
Step 1: The HTML Form & Chart Container
First, we'll create a simple form to capture country names and their medal counts, plus a container where the bar chart will render.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Champions League Medals Bar Chart</title> <style> .chart-container { margin-top: 30px; display: flex; align-items: flex-end; height: 400px; gap: 20px; padding: 20px; border-bottom: 2px solid #333; border-left: 2px solid #333; } .bar { flex: 1; background-color: #2563eb; position: relative; border-radius: 4px 4px 0 0; transition: height 0.3s ease; } .bar-label { position: absolute; bottom: -25px; width: 100%; text-align: center; font-size: 14px; color: #333; } .bar-value { position: absolute; top: -25px; width: 100%; text-align: center; font-weight: bold; color: #2563eb; } form { display: flex; gap: 10px; align-items: center; margin-bottom: 20px; } input { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; } button { padding: 8px 16px; background-color: #2563eb; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #1d4ed8; } </style> </head> <body> <form id="medalForm"> <input type="text" id="countryName" placeholder="Enter country name" required> <input type="number" id="medalCount" placeholder="Medal count" min="1" required> <button type="submit">Add to Chart</button> </form> <div id="chartContainer" class="chart-container"></div> <script> // JavaScript logic goes here </script> </body> </html>
Step 2: JavaScript Logic to Generate the Bar Chart
Now let's add the JavaScript that handles form submission, stores the data, and renders the chart dynamically.
Add this inside the <script> tag:
// Store our medal data in an array const medalData = []; // Get references to DOM elements const form = document.getElementById('medalForm'); const chartContainer = document.getElementById('chartContainer'); // Handle form submission form.addEventListener('submit', function(e) { // Prevent default form reload e.preventDefault(); // Get input values const country = document.getElementById('countryName').value.trim(); const count = parseInt(document.getElementById('medalCount').value); // Validate input (basic check) if (!country || isNaN(count) || count < 1) { alert('Please enter a valid country name and positive medal count!'); return; } // Add data to our array medalData.push({ country, count }); // Reset the form form.reset(); // Re-render the chart renderChart(); }); // Function to render the bar chart function renderChart() { // Clear existing chart chartContainer.innerHTML = ''; // If no data, show a message if (medalData.length === 0) { chartContainer.innerHTML = '<p style="width: 100%; text-align: center; color: #666;">No data added yet. Enter a country and medal count to start!</p>'; return; } // Find the maximum medal count to scale our bars const maxCount = Math.max(...medalData.map(item => item.count)); // Create a bar for each data point medalData.forEach(item => { // Calculate bar height relative to max count (so bars fit in the container) const barHeight = (item.count / maxCount) * 100; // Create bar element const bar = document.createElement('div'); bar.className = 'bar'; bar.style.height = `${barHeight}%`; // Add country label const label = document.createElement('div'); label.className = 'bar-label'; label.textContent = item.country; bar.appendChild(label); // Add medal count value const value = document.createElement('div'); value.className = 'bar-value'; value.textContent = item.count; bar.appendChild(value); // Add bar to chart container chartContainer.appendChild(bar); }); } // Initialize the chart with empty state renderChart();
How It Works
Let's break down the key parts:
- Form Handling: We listen for the form's
submitevent, stop the page from reloading, grab the input values, and validate them to ensure we're getting valid data. - Data Storage: We keep track of all submitted entries in an array (
medalData), so we can build the chart with all accumulated data each time. - Dynamic Chart Rendering: The
renderChart()function does the heavy lifting:- It clears any existing bars to start fresh.
- It calculates the maximum medal count to scale all bars proportionally (so the tallest bar fills the container height).
- For each entry, it creates a bar div with a height based on the scaled value, then adds the country label and medal count on top/bottom.
- It appends each bar to the chart container.
Customization Tips
- Change Colors: Modify the
background-colorvalues in the CSS to match your preferred color scheme. - Adjust Chart Size: Tweak the
heightof.chart-containerin the CSS to make the chart taller/shorter. - Add Animations: The existing CSS has a
transitionon the bar height—you can expand this with more animations if you want. - Edit Validation: Add stricter checks (like preventing duplicate country entries) by adding a check in the form submission handler before pushing to
medalData.
内容的提问来源于stack exchange,提问作者Nayana Chandran
相关产品推荐
相关产品推荐

