Metronic, Bootstrap, Select2,
Hi,
In documentation for Metronic Bootstrap Select2
https://preview.keenthemes.com/html/metronic/docs/forms/select2
we have only examples where users must click on input field with select2 options.
But can how can we create in HTML input field with select2 and autofocus on it like in example from select2 documentation (input box with multiselect)
For instance
When page is loaded cursor must be in input field with select2 options, so users do not need to click on input field with select2 option, they can start entering text after page is loaded.
Pls, I need your help or any suggestion?
Replies (2)
Hi A. Lukic
Yes, you can implement autofocus functionality for Select2 in Metronic. Here, is an approach you can use:
document.addEventListener("DOMContentLoaded", function() {
// Wait for Metronic to initialize Select2 components
setTimeout(function() {
// Target your specific Select2 element
var selectElement = document.querySelector("[data-control="select2"]");
if (selectElement) {
// Focus on the Select2 container
$(selectElement).next(".select2-container").find(".select2-selection").focus();
}
}, 500); // Adjust timing as needed
}); Use setTimeout to ensure Select2 is fully initialized before attempting to focus
Thank you a lot.
$('#item_title').select2({
....
}).on('select2:open', function() {
$('.select2-search__field').focus();
});
setTimeout(function() {
$('#item_title').select2('open');
}, 350);