I tried to create a <select>
with the chzn-select class for the province dropdown.
But this class made my addEventListener not work. If I remove it, the addEventListener will work, but I need it to use this class.
My code:
...
<div id="province_parent"></div>
<script>
(async () => {
await loadProvinceList();
const select = document.createElement('select');
select.id = 'province';
select.name = 'province';
select.className = 'chzn-select';
select.addEventListener('change', () => {
console.log('test');
});
for (let name in provinceNameCodeMap) {
const option = document.createElement('option');
option.value = provinceNameCodeMap[name];
option.textContent = name;
select.appendChild(option);
}
const provinceParent = document.getElementById('province_parent');
provinceParent.innerHTML = '';
provinceParent.appendChild(select);
})();
</script>
I tried these but they did not work. (solutions from Gemini and chatGPT)
select.chosen();
$('#province').chosen();
jQuery(select).chosen();
$('#province').trigger("chosen:updated");
$('#province').trigger('liszt:updated');
I'm working on something that someone else did, so I don't know the details of this class, so I can't create a repeatable code. I'm sorry about that. I hope you can help me.
Assuming you are indeed using jQuery-chosen as your library, handling the change event on it is fairly simple, as per the documentation
You just need to wait until you've added the select to the DOM, then initialise it as a "chosen" object, and then attach the "change" event to that.
Live demo:
var provinceNameCodeMap = { "abcdef": "1", "ghijkl": "2", "mnopqr": "3"};
const select = document.createElement("select")
select.id = "province"
select.name = "province"
select.className = "chzn-select"
for (let name in provinceNameCodeMap) {
const option = document.createElement("option")
option.value = provinceNameCodeMap[name]
option.textContent = name
select.appendChild(option)
}
const provinceParent = document.getElementById("province_parent")
provinceParent.innerHTML = ""
provinceParent.appendChild(select)
//initialise the newly-created select with the "chosen" plugin and then attach the "change" handler to it
$(select).chosen().change(function (e) {
console.log(this.value);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css" />
<div id="province_parent"></div>