Using bootstrap select, I initialize the plugin using the selectpicker so that I don't need to do it manually:
https://developer.snapappointments.com/bootstrap-select/
Add the selectpicker class to your select elements to auto-initialize bootstrap-select.
In my page, this is how I load everything (and same order):
<!doctype html>
<head>
<link href="bootstrap-4.6.min.css" rel="stylesheet">
<link href="bootstrap-select.min.css" rel="stylesheet">
</head>
<body>
<select class="selectpicker">
<option>Mustard</option>
<option>Ketchup</option>
<option>Barbecue</option>
</select>
<script src="jquery-3.6.1.min.js"></script>
<script src="bootstrap-4.6.min.js"></script>
<script src="bootstrap-select.min.js"></script>
<script src="myBootstrapSelectScript.js"></script>
</body>
Then in myBootstrapSelectScript.js I initialize the plugin:
The plugin does load, but it looks like that there are a few milliseconds on load where it's still not ready, because I have a jQuery selector right under the code of initialization, and I get error:
$( document ).ready(function() {
let buttons = $("button.btn.dropdown-toggle");
buttons.each(function() {
$(this).click();
}
});
The $("button.btn.dropdown-toggle") selector is for the button that bootstrap-select creates.
I get error "
Uncaught TypeError: Cannot read properties of undefined (reading 'click')"
But if I use setTimeOut then it works:
setTimeout(() => {
let buttons = $("button.btn.dropdown-toggle");
buttons.each(function() {
$(this).click();
}
}, 2000}
So I tried to use the JavaScript version of the initialization and removed the selectpicker class, and manually initialized it in myBootstrapSelectScript.js:
$( document ).ready(function() {
$('my_select').selectpicker();
let buttons = $("button.btn.dropdown-toggle");
buttons.each(function() {
$(this).click();
}
});
But then I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
So it looks like something is not being loaded correctly, but why? Everything is according to the docs
I think it's the order of your scripts initializing, can you move your Jquery / BS Select scripts into the head, leave BS on the bottom of body; right after your input initialize the BS Select component ie:
This should render BS Select quicker, before the page even renders; give it a try and see - in most cases components that are delayed in initialization stem from the thearchy order of the scripts on the page; I had multiple things before which failed to render on time (adding the timeout is a clever trick/workaround) but when I change my script order I've noticed a huge difference in initialization of components before the entire page loads.