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

如何通过jQuery点击按钮动态生成带选项的Select并获取其值?

Dynamic Select Dropdowns with jQuery: Generate & Capture Selected Values

Got it, let's fix this up for you. You already have a solid start with dynamic text inputs, so adapting that to create select dropdowns and grab their selected values is totally doable. Here's a complete, working example that builds on your existing code:

Full Working Code

<!-- Include jQuery (use your preferred version) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- HTML Structure -->
<button id="btnAdd">Add New Select Dropdown</button>
<div id="SelectContainer"></div>

<script>
$(function () {
    // Function to generate a dynamic select dropdown
    function GetDynamicSelect(selectedValue = "") {
        // Build the select element with predefined options
        return `
            <select class="dynamic-select">
                <option value="">-- Select an Option --</option>
                <option value="option1" ${selectedValue === "option1" ? "selected" : ""}>Option 1</option>
                <option value="option2" ${selectedValue === "option2" ? "selected" : ""}>Option 2</option>
                <option value="option3" ${selectedValue === "option3" ? "selected" : ""}>Option 3</option>
            </select>
            <button class="btnRemove">Remove</button>
        `;
    }

    // Add new select dropdown on button click
    $("#btnAdd").on("click", function () {
        const container = $("#SelectContainer");
        container.append('<div class="select-group">' + GetDynamicSelect("") + '</div>');
    });

    // Capture selected value from ANY dynamic select (event delegation is key here!)
    $(document).on("change", ".dynamic-select", function () {
        const selectedValue = $(this).val();
        const selectIndex = $(this).closest(".select-group").index();
        console.log(`Select #${selectIndex + 1} selected value: ${selectedValue}`);
        
        // If you need to use the value elsewhere, do it here
        // Example: $(this).closest(".select-group").append(`<span>Selected: ${selectedValue}</span>`);
    });

    // Optional: Remove a select dropdown
    $(document).on("click", ".btnRemove", function () {
        $(this).closest(".select-group").remove();
    });
});
</script>

Key Explanations

Let's break down what's happening here to make sure you understand:

  1. Dynamic Select Generation:

    • The GetDynamicSelect function builds a full select element with predefined options. It also accepts an optional selectedValue parameter if you need to set a default selected option when generating the dropdown.
    • We added a "Remove" button for each dropdown to make the interface more user-friendly (you can remove this if you don't need it).
  2. Capturing Selected Values:

    • Since dynamic elements don't exist when the page loads, we can't use bind() directly. Instead, we use event delegation with $(document).on("change", ".dynamic-select", ...). This listens for change events on any element with the dynamic-select class, even if it's added later.
    • Inside the change handler, $(this) refers to the specific select that was changed. We grab its value with .val() and can use it however we need (logging, updating the UI, sending to a server, etc.).
  3. Handling Multiple Dropdowns:

    • We wrap each select in a .select-group div to make it easy to target individual groups (for removing or associating values with their specific dropdown).

Bonus: Get All Selected Values at Once

If you need to collect all selected values from all dynamic dropdowns (e.g., for form submission), you can use this function:

function getAllSelectedValues() {
    const values = [];
    $(".dynamic-select").each(function () {
        const val = $(this).val();
        if (val) values.push(val);
    });
    return values;
}

// Example usage:
// console.log("All selected values:", getAllSelectedValues());

That's it! This should work seamlessly with your existing code structure and let you generate dynamic selects plus capture their values in real time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:45