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

如何将Select2多选下拉框(Multiselect Dropdown)的选中项显示在自定义Div中?

Hey there! I've got you covered on moving those selected Select2 options to your custom .display-here div instead of the default search box. Let's break this down with working code that fits your Bootstrap setup.

Note: Make sure you have included jQuery, Select2, and Bootstrap 5 (since you're using Bootstrap classes) in your project's dependencies before adding this code.


Step 1: Update Your HTML (Minor Tweaks)

We'll keep your existing structure, add an ID to the select for easier targeting, and clean up the placeholder text in your display div:

<div class="card">
  <div class="card-header">Availability</div>
  <div class="card-body">
    <select name="sel" multiple="multiple" class="mul-select" id="availabilitySelect">
      <option value="First">First</option>
      <option value="Second">Second</option>
      <option value="Third">Third</option>
      <option value="Fourth">Fourth</option>
      <option value="Fifth">Fifth</option>
    </select>
    <div class="container display-here mt-3">
      <!-- Selected options will render here -->
    </div>
  </div>
</div>

Step 2: Add the JavaScript Logic

This code initializes Select2, disables its default selected item display, and wires up events to update your custom div in real time:

$(document).ready(function() {
  // Initialize Select2 with custom settings
  $('#availabilitySelect').select2({
    placeholder: "Select options...",
    // Override default selection rendering to keep the search box clean
    templateSelection: function() {
      return ''; // Empty return hides selected items from the search input
    }
  });

  // Helper function to refresh the custom display div
  function updateSelectedOptions() {
    const selectedItems = $('#availabilitySelect').select2('data');
    const displayDiv = $('.display-here');
    displayDiv.empty(); // Clear existing content

    // Loop through selected items and create Bootstrap-style badges
    selectedItems.forEach(item => {
      const badge = $(`
        <span class="badge bg-primary me-2 mb-1">
          ${item.text}
          <button type="button" class="btn-close btn-close-white ms-1" data-value="${item.value}"></button>
        </span>
      `);
      // Add click handler to remove the option when the close button is clicked
      badge.find('.btn-close').on('click', function() {
        const value = $(this).data('value');
        const currentValues = $('#availabilitySelect').val().filter(v => v !== value);
        $('#availabilitySelect').val(currentValues).trigger('change');
      });
      displayDiv.append(badge);
    });
  }

  // Listen for Select2 events to trigger display updates
  $('#availabilitySelect').on('select2:select select2:unselect', function() {
    updateSelectedOptions();
  });
});

Step 3: Optional CSS (Polish the Styling)

Add this to make the Select2 search box fit seamlessly with Bootstrap's design (since we're hiding the default selected items):

/* Adjust Select2 search box to match Bootstrap input styling */
.select2-search--inline {
  width: 100% !important;
}
.select2-search--inline .select2-search__field {
  width: 100% !important;
  border: none;
  outline: none;
  padding: 0.375rem 0.75rem;
}
.select2-container--bootstrap-5 .select2-selection--multiple {
  min-height: calc(2.25rem + 2px);
}

How This Works:

  • templateSelection: This overrides Select2's default behavior of showing selected items inside the search box, keeping it empty except for the placeholder text.
  • Event Listeners: We listen for both select2:select (when an option is picked) and select2:unselect (when an option is removed) to trigger our display update function.
  • Custom Badges: We render Bootstrap-style badges with close buttons, so users can easily remove selections directly from your custom div (the button triggers Select2's value update under the hood).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 23:34:09