ehayun
1
I have a phoenix app that I have a hook with js code like this
import jQuery from "jquery";
import select2 from 'select2';
Worked fine
Now I am creating a new app with Phoenix 1.6.2 and I am getting an error to import the select2 lib
What am I missing?
1 Like
How did you install select2 and jQuery on the 1.6.2 setup?
ehayun
3
with npm
i have package.json
I installed jQuery in the same way and with it I have no problem
ehayun
4
I solve it myself
import $ from "jquery";
import select2 from "select2";
select2($); // <--------------------------------- Have to add this
and also have to add this
@import "../node_modules/bootstrap/scss/bootstrap";
@import "../node_modules/select2/dist/css/select2"; // <------------------
@import "./custom";
5 Likes
Thank you. To clarify, for npm installed select2
, in app.css
, add this:
@import "../node_modules/select2/dist/css/select2.css";
In app.js
, include this:
import jQuery from 'jquery'
import $ from 'jquery'
import select2 from 'select2'
select2($);
then your Hook
can look something like this:
Hook.SelectWeekDays = {
mounted() {
this.initSelect2();
},
selected(hook, event) {
let id = event.params.data.id;
hook.pushEvent("weekday_selected", {weekday: id})
},
initSelect2() {
let hook = this,
$select = jQuery(hook.el).find("select");
$select.select2({
closeOnSelect: false,
placeholder: 'Select Days',
debug: true,
multiple: true,
scrollAfterSelect: true
}).on("select2:select", (d) => hook.selected(hook, d))
return $select;
}
};
2 Likes
ehayun
6
Thanks. I am not so good in explanations
Your explanation is great
dom
7
Does that hook work fine if the websocket reconnects, or do you lose the selection?
ehayun
8
I am adding update too. like this
mounted() {
this.selectIt()
},
updated() {
this.selectIt()
}
Work fine for me
1 Like