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

基于下拉选项动态生成HTML表格的技术实现求助

Hey there! It looks like you're off to a solid start with your first dropdown option, but handling multiple dynamic tables can feel a bit overwhelming. Let's break this down into scalable, reusable steps that will work for all your dropdown choices:

Step 1: Centralize Your Column Definitions

First, create a single object that maps each dropdown value to its corresponding table columns. This keeps all your column logic in one place and makes it easy to update later:

// Define column sets for each dropdown option
const columnConfigs = {
  1: ["Device ID", "Email", "Branch Venue", "Branch Circle", "Branch Address", "Branch Head", "Office Mobile No", "OPS Head", "Mobile No", "Location"],
  2: ["User ID", "Policy Name", "Profile ID", "Profile Name"],
  3: ["Device ID", "Patch Name", "Install Date", "Status"], // Adjust to your actual columns
  4: ["Device ID", "Battery Level", "Charging Status", "Last Updated"],
  5: ["Device ID", "Network Type", "Signal Strength", "IP Address"],
  6: ["Device ID", "Status", "Last Check-in", "OS Version"],
  7: ["Device ID", "App Name", "Version", "Status"]
};
Step 2: Reset the Table on Dropdown Change

Every time the user selects a new option, we need to clear the existing table and destroy any active DataTable instance to avoid conflicts:

$('#selectInfo').on('change', function() {
  const selectedValue = $(this).val();
  const $table = $('#tab');

  // Destroy existing DataTable if it exists
  if ($.fn.DataTable.isDataTable($table)) {
    $table.DataTable().destroy();
  }

  // Clear old table content
  $table.find('thead').empty();
  $table.find('tbody').empty();

  // Build new header from column config
  const columns = columnConfigs[selectedValue];
  if (columns) {
    let headerHtml = '<thead><tr>';
    columns.forEach(col => {
      headerHtml += `<th>${col}</th>`;
    });
    headerHtml += '</tr></thead>';
    $table.append(headerHtml);
  }
});
Step 3: Dynamic Row Rendering in AJAX Response

Update your AJAX success handler to render rows based on the selected dropdown option. Create a reusable function to handle row generation for each case:

// Reusable function to render rows based on selected option
function renderTableRows(selectedValue, response) {
  const $tbody = $('#tab tbody');
  $tbody.empty();

  switch(selectedValue) {
    case '1':
      // Your existing row logic for Register Device
      response.forEach(value => {
        const row = `<tr>
          <td>${value.device_id}</td>
          <td>${value.email}</td>
          <td>${value.city}</td>
          <td>${value.first_name}</td>
          <td>${value.address}</td>
          <td>${value.branch_head}</td>
          <td>${value.branch_mobile_no}</td>
          <td>${value.office_head}</td>
          <td>${value.office_mobile_no}</td>
          <td>${value.location_of_sbk}</td>
        </tr>`;
        $tbody.append(row);
      });
      break;
    case '2':
      // Row logic for Device Assign policies
      response.forEach(value => {
        const row = `<tr>
          <td>${value.user_id}</td> // Match your actual API response fields
          <td>${value.policy_name}</td>
          <td>${value.profile_id}</td>
          <td>${value.profile_name}</td>
        </tr>`;
        $tbody.append(row);
      });
      break;
    // Add cases for options 3-7 here, matching your API's response structure
    case '3':
      response.forEach(value => {
        const row = `<tr>
          <td>${value.device_id}</td>
          <td>${value.patch_name}</td>
          <td>${value.install_date}</td>
          <td>${value.status}</td>
        </tr>`;
        $tbody.append(row);
      });
      break;
    // Repeat for options 4-7...
  }
}

Then update your AJAX success callback to use this function:

success: function(response) {
  const selectedValue = $('#selectInfo').val();
  
  // Render the correct rows for the selected option
  renderTableRows(selectedValue, response);
  
  // Initialize DataTable with the new content
  $("#tab").DataTable();
  
  $('#tab').removeClass('display').addClass('table table-hover table compact');
  console.log(response);
},
Additional Tips
  • PHP Endpoint: Make sure your dashboard.php file checks the info parameter from the form and returns the correct data set for each option.
  • Empty Responses: Add a check in the success handler to show a "No data found" message if the response is empty.
  • Field Validation: Ensure that the API response fields match exactly what you're using in the row templates (e.g., value.user_id should exist in the response for option 2).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:51:54