-
-
Notifications
You must be signed in to change notification settings - Fork 573
Expand file tree
/
Copy pathselect2_controller.js
More file actions
48 lines (43 loc) · 1.52 KB
/
select2_controller.js
File metadata and controls
48 lines (43 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { Controller } from "@hotwired/stimulus"
import $ from 'jquery';
import "select2"
export default class extends Controller {
static values = {
config: { type: Object, default: {} },
hideDropdown: { type: Boolean, default: false }
};
connect() {
const select2 = $(this.element).select2(this.configValue);
if (select2.data('select2')) select2.data('select2').$selection.addClass('form-select p-0')
if (this.hideDropdownValue) {
select2.on('select2:open', function (e) {
$('.select2-container--open .select2-dropdown--below').css('display','none');
});
}
/**
* This is a workaround to auto focus on the select2 input when it is opened.
*/
$(this.element).on('select2:open', function (e) {
let select2Instance = $(e.target).data('select2');
if (select2Instance) {
let searchField = select2Instance.dropdown.$search || select2Instance.selection.$search;
if (searchField) {
searchField.focus();
}
}
});
/**
* This is a workaround to prevent select2 from filling in an existing
* value even when you try to remove everything. This solution was found at
* https://github.com/select2/select2/issues/3320#issuecomment-1440268574
*/
if ($(this.element).prop('multiple')) {
select2.on("select2:unselecting", function (e) {
$(this).on("select2:opening", function (ev) {
ev.preventDefault();
$(this).off("select2:opening");
});
});
}
}
}