-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect2cascade.js
More file actions
95 lines (82 loc) · 3.07 KB
/
select2cascade.js
File metadata and controls
95 lines (82 loc) · 3.07 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Select2Cascade {
constructor(parent, child, options) {
this.parent = parent;
this.child = child;
this.options = options;
this.options.text = this.options.text === undefined ? 'text' : this.options.text;
this.options.id = this.options.id === undefined ? 'id' : this.options.id;
}
changeDisabled(value) {
this.child.prop('disabled', value);
}
/**
* Adiciona o evento de select
* fazendo o Ajax para buscar os dados
* */
addSelectEvent() {
this.parent.on('select2:select', () => {
this.changeDisabled(true);
let value = this.parent.val();
if (value) {
$.ajax({
url: this.options.url,
type: 'GET',
dataType: 'json',
data: {
search: value
}
}).done((response) => {
if(this.options.callback){
this.options.callback();
}
//esvazia o select dependente
this.child
.empty()
.prepend('<option></option>')
.trigger('change');
response.results.forEach((value) => {
var persist = [];
// verifica se há valores persistidos
if (this.child.data('persist')) {
var persistValue = this.child.data('persist').toString().split(',');
persist = persistValue.length > 0 ? persistValue : [];
}
// preenche valores
this.child.append($('<option>', {
value: value[this.options.id],
text: value[this.options.text],
selected: persist.includes(value[this.options.id].toString()) ? 'selected' : false
}));
});
this.child.trigger('change').trigger('select2:select');
this.changeDisabled(false);
}).fail(function (error) {
console.log(error);
})
}
})
}
/**
* Verifica se há uma persitência no primeiro campo
* disparando o select caso haja
* */
checkPersistedValue(){
const persist = this.parent.data('persist');
let values = [];
// verifica se há valores persistidos
if (persist) {
const persistValue = persist.toString().split(',');
values = persistValue.length > 0 ? persistValue : [];
this.parent.val(values).trigger('change').trigger('select2:select');
}
}
init() {
if (this.parent && this.child && this.options) {
this.changeDisabled(true);
this.addSelectEvent();
this.checkPersistedValue();
}
return this;
}
}
window.Select2Cascade = Select2Cascade;