You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jinja2从列表动态生成表单输入框与标签?

动态生成表单解决方案

Got it, let's tackle this dynamic form generation problem. Based on your requirement, here's a clean, Bootstrap-friendly solution that generates forms on button click using your predefined field lists:

1. HTML基础结构

First, we'll set up the button group and a container to hold the dynamically generated form:

<!-- Button Group to trigger form generation -->
<div class="btn-group mb-3" role="group">
  <button type="button" class="btn btn-primary" data-form="A">A</button>
  <button type="button" class="btn btn-primary" data-form="B">B</button>
  <button type="button" class="btn btn-primary" data-form="C">C</button>
</div>

<!-- Container where the form will be injected -->
<div id="form-container"></div>

2. JavaScript实现逻辑

Next, we'll write the JS to handle button clicks, fetch the corresponding field list, and build the form dynamically:

// Define your field lists mapped to their button labels
const formFieldSets = {
  A: ["name", "city", "state", "phone"],
  B: ["album", "artist", "genre"],
  C: ["title", "author", "category", "subcategory"]
};

// Get references to DOM elements
const formContainer = document.getElementById('form-container');
const formTriggerButtons = document.querySelectorAll('.btn-group .btn');

// Add click event listeners to each button
formTriggerButtons.forEach(button => {
  button.addEventListener('click', () => {
    // Get the field set key from the button's data attribute
    const fieldSetKey = button.getAttribute('data-form');
    const fields = formFieldSets[fieldSetKey];
    
    // Clear any existing form in the container
    formContainer.innerHTML = '';
    
    // Create the base form element
    const dynamicForm = document.createElement('form');
    
    // Loop through each field to build form groups
    fields.forEach(field => {
      // Create form group wrapper (Bootstrap row layout)
      const formGroup = document.createElement('div');
      formGroup.classList.add('form-group', 'row');
      
      // Create label element
      const fieldLabel = document.createElement('label');
      fieldLabel.htmlFor = field;
      fieldLabel.classList.add('col-sm-2', 'col-form-label');
      // Capitalize the first letter for better UI
      fieldLabel.textContent = field.charAt(0).toUpperCase() + field.slice(1);
      
      // Create input column wrapper
      const inputColumn = document.createElement('div');
      inputColumn.classList.add('col-sm-10');
      
      // Create input element
      const fieldInput = document.createElement('input');
      fieldInput.type = field === 'phone' ? 'tel' : 'text'; // Adjust input type for phone
      fieldInput.classList.add('form-control');
      fieldInput.id = field;
      fieldInput.name = field;
      fieldInput.placeholder = `Enter your ${field}`;
      
      // Assemble the form group
      inputColumn.appendChild(fieldInput);
      formGroup.appendChild(fieldLabel);
      formGroup.appendChild(inputColumn);
      dynamicForm.appendChild(formGroup);
    });
    
    // Add a submit button (optional but useful)
    const submitButton = document.createElement('button');
    submitButton.type = 'submit';
    submitButton.classList.add('btn', 'btn-success', 'mt-3');
    submitButton.textContent = 'Submit Form';
    
    // Attach submit handler if needed (example)
    dynamicForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const formData = new FormData(dynamicForm);
      console.log('Form submitted:', Object.fromEntries(formData));
      // Add your submission logic here
    });
    
    dynamicForm.appendChild(submitButton);
    
    // Inject the completed form into the container
    formContainer.appendChild(dynamicForm);
  });
});

3. Key Notes

  • Bootstrap Dependence: The code uses Bootstrap's grid and form classes for styling. If you're not using Bootstrap, just replace the form-group row, col-sm-2, etc., with your own CSS classes for layout.
  • Input Type Customization: I added a small tweak to set the phone field to tel type for better mobile UX—you can adjust this or add other input types (like email) if needed for other fields.
  • Form Submission: The example includes a basic submit handler that logs form data to the console. You can replace this with your own API call or form processing logic.

内容的提问来源于stack exchange,提问作者DevEx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:25:35