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