Select2 on change event is not working
Hello,
I'm using Metronic 8 with Symfony but I can't get select2 to work properly.
<select data-hide-search="true" multiple="multiple" data-control="select2" data-placeholder="Budget approximatif" class="form-select form-select-solid" id="filterBudget">
<option></option>
{% for value, label in aBudgets %}
<option value="{{ value }}">{{ label }}</option>
{% endfor %}
</select> Select2 is correctly instantiated correctly and working but the on change event is not triggering.
$("#filterBudget").on("change", function (e) { console.log("select2:select"); }); All metronic sources are correctly loaded in my base twig template like this
<!--begin::Global Javascript Bundle(used by all pages)-->
<script src="{{ asset("assets/plugins/global/plugins.bundle.js") }}"></script>
<script src="{{ asset("assets/js/scripts.bundle.js") }}"></script>
<!--end::Global Javascript Bundle(used by all pages)--> And then, I load my custom javascript.
<img src="
Thanks for your help
Replies (5)
It seems like you might be facing an issue where the Select2 library is not being correctly loaded or initialized.
You can wrap your script in a $(document).ready block to ensure that it executes after the DOM is ready.
$(document).ready(function () {
$("#filterBudget").select2().on("change", function (e) {
console.log("select2:select");
});
}); Hi,
Instead of relying on the on method, try using the change event directly on the Select2 instance.
$("#filterBudget").select2().on("change", function (e) {
console.log("select2:select");
}); This should also capture the change event of the Select2.
Hi,
When I try to use the select2() function in javascript instead of HTML data-attributes, I have the error "select2 is not a function".
Thanks for your help
Hi,
Instead of relying on the generic change event, you can try using Select2-specific events. For example, you can use the select2:select event directly.
$("#filterBudget").on("select2:select", function (e) {
console.log("select2:select");
}); Hi,
Thanks for the reply ! I tried this too, but still not working unfortunately.