$(document).ready(function () {
const $listLinea = $('#listLinea');
const $listItem = $('#listItem');
const $tpRegistro = $('#tpRegistro');
// destruye select2 si existe (seguro)
function destroyIfExists($el) {
if ($el && $el.length && $el.data('select2')) {
try { $el.select2('destroy'); } catch (e) { /* ignore */ }
}
}
// sincroniza ancho del contenedor Select2 con el <select> base
// sincroniza ancho del contenedor Select2 con el <select> base
function syncWidth($el) {
if (!$el || !$el.length) return;
const $container = $el.next('.select2-container');
if (!$container.length) return;
// tomar el ancho real del select
const w = Math.ceil($el.outerWidth());
// aplicar el mismo ancho exacto (no -10)
$container.css({
width: w + 'px',
'min-width': w + 'px',
'max-width': w + 'px',
'box-sizing': 'border-box',
display: 'block'
});
$container.find('.select2-selection--single').css({
width: w + 'px',
'min-width': w + 'px',
'max-width': w + 'px',
'box-sizing': 'border-box'
});
}
// inicializa Select2 usando el ancho en línea del <select> (style)
function inicializarSelect2($elemento) {
if (!$elemento || !$elemento.length) return;
// asegurar ancho en el propio <select> antes de inicializar
$elemento.css('width', '100%');
destroyIfExists($elemento);
$elemento.select2({
theme: "bootstrap-5",
width: 'style', // toma el width del elemento <select> (inline style)
dropdownAutoWidth: false // evita que el dropdown cambie el ancho
});
// sincronizar inmediatamente y con pequeño delay
syncWidth($elemento);
setTimeout(function () { syncWidth($elemento); }, 60);
// volver a sincronizar en eventos relevantes y resize
$elemento.off('.select2sync').on('select2:open.select2sync select2:closing.select2sync select2:select.select2sync change.select2sync', function () {
syncWidth($elemento);
});
$(window).off('resize.select2sync-' + ($elemento.attr('id') || 'noid'))
.on('resize.select2sync-' + ($elemento.attr('id') || 'noid'), function () { syncWidth($elemento); });
}
// === tu lógica AJAX pero llamando a inicializarSelect2 al final ===
// Cargar líneas desde PHP
function cargarLinea() {
$.ajax({
type: "GET",
url: "../models/selectDinamico.php",
success: function (response) {
let lineas;
try { lineas = JSON.parse(response); }
catch (e) { console.error('Error parseando lineas:', e, response); return; }
let template = '<option value="" selected disabled hidden>--Seleccione--</option>';
lineas.forEach(linea => {
template += `<option value="${linea.codID}">${linea.codLitem}--${linea.nomLitem}</option>`;
});
// destruir antes y actualizar html
destroyIfExists($listLinea);
$listLinea.html(template);
// inicializar select2 y sincronizar ancho
inicializarSelect2($listLinea);
},
error: function (xhr) { console.error('Error AJAX cargarLinea:', xhr.responseText || xhr.statusText); }
});
}
// Cargar items según la línea seleccionada
function cargarItems(codLinea) {
$.ajax({
type: "POST",
url: "../models/selectDinamico.php",
data: { codigoLinea: codLinea },
success: function (response) {
let items;
try { items = JSON.parse(response); }
catch (e) { console.error('Error parseando items:', e, response); return; }
let template = '<option value="" selected disabled>--Seleccione--</option>';
items.forEach(item => {
template += `<option value="${item.codItem}">${item.codLinea}--${item.nomLinea}</option>`;
});
destroyIfExists($listItem);
$listItem.html(template);
// inicializar select2 y sincronizar ancho
inicializarSelect2($listItem);
},
error: function (xhr) { console.error('Error AJAX cargarItems:', xhr.responseText || xhr.statusText); }
});
}
// Evento al cambiar línea
$listLinea.on('change', function () {
const codLinea = $(this).val();
if (!codLinea) return;
cargarItems(codLinea);
if ($tpRegistro.val() !== '2') return;
});
// Evento al cambiar tipo de registro
$tpRegistro.on('change', function () {
if ($(this).val() !== '2') {
$listLinea.prop('disabled', true);
$listItem.prop('disabled', true);
} else {
$listLinea.prop('disabled', false);
$listItem.prop('disabled', false);
}
});
// INIT: carga las líneas y prepara selects vacíos
cargarLinea();
// Inicializar vacíos (por si el template no carga rápidamente)
inicializarSelect2($listLinea);
inicializarSelect2($listItem);
// DEBUG opcional: si quieres ver medidas en consola al seleccionar (comenta si no quieres)
$listLinea.on('select2:select', function () { console.log('[DEBUG] listLinea:', $listLinea.outerWidth(), $listLinea.next('.select2-container').outerWidth()); });
$listItem.on('select2:select', function () { console.log('[DEBUG] listItem:', $listItem.outerWidth(), $listItem.next('.select2-container').outerWidth()); });
});