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

基于数据库的动态下拉框联动填充输入框技术实现咨询

Dynamic Dropdown to Input Fields Linkage for Dynamic Concert Data

Hey there! I've got you covered on this dynamic linkage issue. Since your dropdown is generated dynamically with PHP (and can have 2-20 options), we'll use a backend AJAX endpoint + frontend JavaScript approach that works smoothly no matter how many options you have. Here's how to implement it:


1. Create a Backend API Endpoint (PHP)

First, we need a way to fetch full concert data when a dropdown option is selected. Create a new PHP file (e.g., get-concert-data.php) that accepts a concert ID and returns the corresponding data as JSON:

<?php
// Connect to your database (adjust credentials to match your setup)
$pdo = new PDO('mysql:host=your_host;dbname=your_db', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Get the concert ID from the request
if (isset($_GET['id'])) {
    $concertId = $_GET['id'];
    
    // Fetch the matching concert data
    $stmt = $pdo->prepare("SELECT artiestnaam, locatie, evenement FROM concerts WHERE id = :id");
    $stmt->bindParam(':id', $concertId);
    $stmt->execute();
    $concertData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Return data as JSON
    header('Content-Type: application/json');
    echo json_encode($concertData);
} else {
    // Return error if no ID is provided
    header('HTTP/1.1 400 Bad Request');
    echo json_encode(['error' => 'Concert ID not provided']);
}
?>

2. Update Your Frontend HTML

Modify your existing dropdown and add the input fields that need to be populated. Make sure each input has a unique ID matching your database field names:

<!-- Your dynamic dropdown (added an ID for JS targeting) -->
<select name="concert" class="form-control" id="concertDropdown">
    <?php while ($row = $concertResult->fetch()) { ?>
        <option value="<?php echo $row['id']; ?>">
            Id: <?php echo $row['id']; ?> Artiest naam: <?php echo $row['artiestnaam']; ?> Locatie: <?php echo $row['locatie']; ?> Evenement: <?php echo $row['evenement']; ?>
        </option>
    <?php } ?>
</select>

<!-- Input fields to populate -->
<div class="mt-3">
    <label for="artiestnaam">Artiest naam:</label>
    <input type="text" id="artiestnaam" name="artiestnaam" class="form-control">
    
    <label for="locatie" class="mt-2">Locatie:</label>
    <input type="text" id="locatie" name="locatie" class="form-control">
    
    <label for="evenement" class="mt-2">Evenement:</label>
    <input type="text" id="evenement" name="evenement" class="form-control">
</div>

3. Add JavaScript for Dynamic Linkage

Add this script to your page (either in a <script> tag at the end of the body or an external JS file). It listens for dropdown changes, fetches the matching data, and populates the inputs:

// Wait for the DOM to fully load before running code
document.addEventListener('DOMContentLoaded', function() {
    // Grab elements from the DOM
    const dropdown = document.getElementById('concertDropdown');
    const artiestnaamInput = document.getElementById('artiestnaam');
    const locatieInput = document.getElementById('locatie');
    const evenementInput = document.getElementById('evenement');

    // Helper function to populate inputs with concert data
    function populateInputs(data) {
        artiestnaamInput.value = data.artiestnaam || '';
        locatieInput.value = data.locatie || '';
        evenementInput.value = data.evenement || '';
    }

    // Listen for when the dropdown selection changes
    dropdown.addEventListener('change', function() {
        const selectedId = this.value;
        
        if (selectedId) {
            // Fetch data from our backend API
            fetch(`get-concert-data.php?id=${selectedId}`)
                .then(response => {
                    if (!response.ok) throw new Error('Network request failed');
                    return response.json();
                })
                .then(data => {
                    if (!data.error) {
                        populateInputs(data);
                    } else {
                        console.error('Error:', data.error);
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                });
        } else {
            // Clear inputs if no option is selected
            populateInputs({});
        }
    });

    // Optional: Auto-populate inputs on page load if a default option is selected
    if (dropdown.value) {
        dropdown.dispatchEvent(new Event('change'));
    }
});

Key Details to Note

  • Flexibility: This approach works for any number of dropdown options (2-20+), since it dynamically fetches data based on the selected ID instead of relying on static preloaded data.
  • User Edits: Once inputs are populated, users can freely modify the values—this code only sets the initial value, it doesn't lock the inputs from being edited.
  • Error Handling: The code includes basic error handling for network issues or missing data, which you can expand based on your specific needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:11:34