javascripthtmltwitter-bootstrapdrop-down-menubootstrap-5

Refresh dynamic select box in JavaScript with Bootstrap 5


Using bootstrap 5, I have the following html:

<select class="form-select">
<option hidden="hidden">17 kW</option>
<option>18 kW</option>
<option>19 kW</option>
<option>20 kW</option>
<option>22 kW</option>
<option selected="selected">24 kW</option>
<option>26 kW</option>
<option>28 kW</option>
<option>30 kW</option>
<option>32 kW</option>
<option hidden="hidden">34 kW</option>
</select>

Note the two hidden options.

The first time I click the select box I get the image on the left. The next time I click the select box I get the image on the right. Using Chrome as the browser.

Bootstrap select dropdown

Is there a way in javascript or jquery to refresh the select box to ensure proper display, before the box is displayed for the first time?


Solution

  • To ensure proper display on the first click, you can use JavaScript to essentially "pre-initialize" the select element.

    // Function to refresh the select dropdown
    function refreshSelectDropdown(selectElement) {
      // Force the browser to recalculate the dropdown layout
      selectElement.style.display = 'none';
      setTimeout(() => {
        selectElement.style.display = '';
      }, 0);
    }
    
    // Use when the DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
      // Get all select elements with the class 'form-select'
      const selects = document.querySelectorAll('.form-select');
      
      // Apply the refresh to each select element
      selects.forEach(refreshSelectDropdown);
    });

    Another approach is to trigger a quick focus/blur event sequence on the select element:

    document.addEventListener('DOMContentLoaded', function() {
      const selects = document.querySelectorAll('.form-select');
      
      selects.forEach(select => {
        // Focus and immediately blur to force redraw
        select.focus();
        select.blur();
      });
    });

    These methods should help ensure consistent rendering before the user first interacts with the dropdown.