Skip to content

Instantly share code, notes, and snippets.

@tofikhidayatxyz
Last active January 5, 2023 13:35
Show Gist options
  • Select an option

  • Save tofikhidayatxyz/57ac5014b75797bd93a20330a858cf22 to your computer and use it in GitHub Desktop.

Select an option

Save tofikhidayatxyz/57ac5014b75797bd93a20330a858cf22 to your computer and use it in GitHub Desktop.
Rendering and watch select2 using alpine.js
class Select2Alpine {
constructor(el) {
this.el = document.querySelector(el);
if (!this.el) {
throw `Element ${el} not found`;
}
}
init() {
this.render();
return this;
}
watch(callback) {
this.select2.on('select2:select', callback);
return this;
}
setValue(value) {
this.select2.val(value).trigger('change');
return this;
}
setData(data) {
this.el.innerHTML = '';
data.forEach((dt) => {
const optionData = new Option();
optionData.value = dt.value;
optionData.textContent = dt.label;
optionData.selected = dt.selected;
this.el.appendChild(optionData);
});
return this;
}
render() {
this.select2 = $(this.el).select2();
return this;
}
destroy() {
this.select2.select2('destroy');
return this;
}
reRender() {
this.destroy();
this.render();
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment