cogido select2 de alvaro

This commit is contained in:
Jaime Jimenez
2024-10-14 13:58:50 +02:00
parent 7ad3133a15
commit 287335dc6b

View File

@ -1,77 +1,72 @@
class ClassSelect2 {
constructor(domItem, url, placeholder = "", delay = 60, text_field = 'nombre', id_field = 'id', params={}) {
this.domItem = domItem;
this.url = url;
this.placeholder = placeholder;
this.delay = delay;
this.text_field = text_field;
this.id_field = id_field;
this.params = params;
}
init() {
this.domItem.select2({
allowClear: false,
placeholder: this.placeholder,
ajax: {
url: this.url,
type: 'post',
dataType: 'json',
data: (params) => {
let d = {
id: this.id_field,
text: this.text_field,
searchTerm: params.term,
};
for (let key in this.params) {
d[key] = this.params[key];
}
return d;
},
delay: this.delay,
processResults: function (response) {
return {
results: response.menu
};
},
cache: true
}
});
}
// Método para obtener el valor seleccionado
getValue() {
return this.domItem.val();
}
// Método para establecer el valor seleccionado
setValue(value) {
this.domItem.val(value).trigger('change');
}
setParams(params) {
this.params = params;
}
clear() {
this.domItem.val(null).trigger('change');
}
// Método para oculatar el select2
hide() {
this.domItem.select2('close');
this.domItem.next('.select2-container').hide();
}
// Método para mostrar el select2
show() {
this.domItem.next('.select2-container').show();
}
}
export default ClassSelect2;
/**
*
* @param {DOM} domItem
* @param {String} url
* @param {String} placeholder
*/
let ClassSelect = function (domItem, url, placeholder, allowClear = false) {
this.url = url;
this.item = domItem;
this.config = {
placeholder: placeholder,
allowClear: allowClear,
dropdownParent: domItem.parent(),
ajax: {
url: () => {
return this.url;
},
data: function (params) {
return {
q: $.trim(params.term),
};
},
processResults: function (data) {
return {
results: $.map(data, function (obj) {
return {
id: obj.id,
text: obj.nombre ?? obj.name,
desc: obj.description,
};
}),
};
},
cache: true,
},
};
this.init = function () {
if (this.item.length) {
this.item = this.item.select2(this.config);
$.fn.modal.Constructor.prototype.enforceFocus = function () {};
}
};
this.setOption = function (id, nombre) {
var newOption = new Option(nombre , id, false, false);
this.item.append(newOption);
this.item.val(id).trigger("change");
};
this.reset = function () {
this.item.val(null).trigger("change");
};
this.getVal = function () {
return this.item.val();
};
this.setVal = function (val) {
return this.item.val(val).trigger("change");
};
this.empty = function () {
return this.item.empty().trigger("change");
};
this.readOnly = function () {
this.item.enable(false);
};
this.enable = () => {
this.item.enable(true);
};
this.fixWithScroll = function () {};
this.getText = () => {
return this.item.find(":selected").text();
};
};
export default ClassSelect;