“Select All” Option Not Appearing as the First Item in TomSelect Dropdown

I’m using TomSelect to create a multi-select dropdown in my project. I’ve added a “Select All” option and I’m trying to ensure that it always appears as the first item in the dropdown. However, despite my efforts, the “Select All” option does not consistently appear at the top of the list.

Here’s my current implementation:

function renderOptionItem(item, escape) {
  let img = item.src ? `<img class="me-2 tomselect-image" src="${escape(item.src)}" alt="icon" />` : '';
  let subtext = item.subtext ? `<div class="text-muted">${escape(item.subtext)}</div>` : '';
  return `<div class="d-flex align-items-center">
        ${img}
        <div>
        <div>${escape(item.text)}</div>
        ${subtext}
        </div>
      </div>`;
}

function updateSelectedItemsLabel(tomSelectInstance) {
  const selectedItems = tomSelectInstance.getValue();
  const selectedCount = selectedItems.length;
  const control = tomSelectInstance.control.querySelector('.items');

  if (selectedCount > 3 && control) {
    // Clear the control and add the summary item
    control.innerHTML = `<div class="item">Valgt ${selectedCount} elementer</div>`;
  } else {
    tomSelectInstance.refreshItems(); // Refresh to show actual selected items
  }

  // Update the "Select all" checkbox state
  const selectAllCheckbox = tomSelectInstance.dropdown_content.querySelector('.option[data-value="select-all"] input[type="checkbox"]');
  if (selectAllCheckbox) {
    const allItemValues = Object.keys(tomSelectInstance.options).filter(value => value !== 'select-all');
    selectAllCheckbox.checked = selectedItems.length === allItemValues.length;

    // Set a specific ID to the checkbox
    selectAllCheckbox.id = 'groupSelect-opt-0'; // Replace 'your-specific-id' with the desired ID
  }
}

function handleSelectAll(tomSelectInstance) {
  const allItems = tomSelectInstance.options;
  const allItemValues = Object.keys(allItems).filter(value => value !== 'select-all');
  const selectedItems = tomSelectInstance.getValue();

  if (selectedItems.length === allItemValues.length) {
    tomSelectInstance.clear(); // Deselect all if already selected
  } else {
    tomSelectInstance.setValue(allItemValues); // Select all
  }
}

function initializeTomSelect(selector, isSingleSelect = false) {
  const tomSelectInstance = new TomSelect(selector, {
    valueField: 'value',
    labelField: 'text',
    searchField: ['text', 'subtext'],
    render: {
      option: (item, escape) => {
        if (item.value === 'select-all') {
          return `<div class="d-flex align-items-center option">
                <div>Vælg alle</div>
              </div>`;
        } else {
          return renderOptionItem(item, escape);
        }
      },
      item: renderOptionItem
    },
    plugins: {
      'remove_button': {},
      'dropdown_input': {},
      'checkbox_options': {},
      'clear_button': {
        title: 'Ryd valgte' // Danish for "Clear selected"
      },
    },
    maxItems: isSingleSelect ? 1 : null,
    placeholder: isSingleSelect ? 'Vælg en mulighed...' : 'Vælg nogle muligheder...',
    create: false,
    allowEmptyOption: false, // Disallow empty options
    onInitialize: function() {
      if (isSingleSelect) {
        this.clear(); // Ensure no default selection
      }
      updateSelectedItemsLabel(this);

      // Add "Select all" option first
      this.addOption({ value: 'select-all', text: 'Vælg alle' });
      this.refreshOptions(false);

      // Ensure "Select all" is the first item
      const dropdownContent = this.dropdown_content;
      const selectAllOption = this.getOption('select-all');
      if (selectAllOption) {
        dropdownContent.insertBefore(selectAllOption, dropdownContent.firstChild);
      }

      dropdownContent.addEventListener('click', (event) => {
        const optionElement = event.target.closest('.option');
        if (optionElement && optionElement.getAttribute('data-value') === 'select-all') {
          event.stopPropagation(); // Prevent the dropdown from closing
          handleSelectAll(this);
          updateSelectedItemsLabel(this);
        }
      });
    },
    onItemAdd: function(value) {
      if (value !== 'select-all') {
        updateSelectedItemsLabel(this);
      }
    },
    onItemRemove: function() {
      updateSelectedItemsLabel(this);
    }
  });

  function moveSelectAllToTop(instance) {
    const dropdownContent = instance.dropdown_content;
    const selectAllOption = instance.getOption('select-all');
    if (selectAllOption) {
      dropdownContent.insertBefore(selectAllOption, dropdownContent.firstChild);
    }
  }

  // Handle the clear button functionality
  tomSelectInstance.on('clear', function() {
    tomSelectInstance.refreshItems();
  });

  // Handle changes to re-enable item removal if more than 3 selected
  tomSelectInstance.on('change', function() {
    const selectedItems = tomSelectInstance.getValue();
    const control = tomSelectInstance.control.querySelector('.items');

    if (selectedItems.length <= 3 && control && control.innerHTML.includes('elementer')) {
      tomSelectInstance.refreshItems(); // Refresh to show actual selected items
    }

    // Update the "Select all" checkbox state
    const selectAllCheckbox = tomSelectInstance.dropdown_content.querySelector('.option[data-value="select-all"] input[type="checkbox"]');
    if (selectAllCheckbox) {
      const allItemValues = Object.keys(tomSelectInstance.options).filter(value => value !== 'select-all');
      selectAllCheckbox.checked = selectedItems.length === allItemValues.length;
    }
  });
}

// Initialize Tom Select elements
document.addEventListener('DOMContentLoaded', function() {
  initializeTomSelect('#employeeSelect');
  initializeTomSelect('#entryTypeSelect', true); // Set isSingleSelect to true for entryTypeSelect
});

The Issue
Despite the code snippet above, the “Select All” option does not always appear as the first item in the dropdown. I’ve tried the following approaches:

  1. Adding the “Select All” option first using this.addOption.
  2. Manually moving the “Select All” option to the top using
    insertBefore.

However, these methods do not consistently result in the “Select All” option being at the top.

Expected Behavior
The “Select All” option should consistently appear as the first item in the dropdown list whenever the dropdown is opened.

Request for Help
I’m looking for guidance on how to ensure the “Select All” option always appears at the top of the dropdown list. Any insights or suggestions on how to achieve this would be greatly appreciated.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật