Select2 дважды отображается в модальном режиме при первом открытииJquery

Программирование на jquery
Ответить Пред. темаСлед. тема
Anonymous
 Select2 дважды отображается в модальном режиме при первом открытии

Сообщение Anonymous »

У меня есть модальное окно, в котором это модальное окно отображается содержимое динамически с помощью js. модальный HTML-код выглядит следующим образом:

Код: Выделить всё





Modal Title[/b][b]                
×


@* Modal content will be injected here *@




Затем модальное окно добавляет содержимое внутрь «modalBody», используя предоставленный мной шаблон. Один из примеров шаблона тела контента:

Код: Выделить всё




Year






Level


@if (Model.EduLevelDropdownList != null)
{
foreach (var level in Model.EduLevelDropdownList)
{
@level.CodeName
}
}








Institution Name


Other
@if (Model.EduInstitutionDropdownList != null)
{
foreach (var institute in Model.EduInstitutionDropdownList)
{
@institute.CodeName
}
}










[/i] Add


[i][/i] Update



Это мой код JavaScript, который динамически изменяет содержимое модального окна:

Код: Выделить всё

// Function to load different template content into the modal
function loadModalContent(templateId, title) {

// Clear previous content to prevent duplication
$('#modalBody').empty();
$('#modalBody .select2normalWithouClear').select2('destroy');

// Load new content and set the title
var templateContent = $('#' + templateId).html();  // Get the content of the template
$('#modalBody').html(templateContent);             // Inject content into the modal body
$('#modalTitle').text(title);                      // Set the modal title

$('#modalBody .select2normalWithouClear').select2({
placeholder: $(this).data('placeholder')
});

$('.edu-instituteNameOther').hide();

$('#modal').modal('show');                          // Show the modal
}

// Event listener for buttons that trigger the modal with different templates
$(document).on('click', '.openModalBtn', function () {
var templateId = $(this).data('template');         // Get the template to load
var modalTitle = $(this).data('title');            // Get the title for the modal

loadModalContent(templateId, modalTitle);          // Call the function to load the content

TMCEWoFileUpl("250", "");
});

Проблема в том, что когда я открываю модальное окно после загрузки страницы, оно отображает два раскрывающихся списка: один работает правильно, а другой кажется дубликатом и не работает. Однако, когда я открываю модальное окно во второй раз, раскрывающийся список отображается правильно и не дублируется. Может ли кто-нибудь помочь мне это исправить?
Я пробовал инициализировать его вне модального окна, но это все равно не работает.
Это живая демонстрация:

Код: Выделить всё

// Function to load different template content into the modal
function loadModalContent(templateId, title) {

// Clear previous content to prevent duplication
$('#modalBody').empty();
$('#modalBody .select2normalWithouClear').select2('destroy');

// Load new content and set the title
var templateContent = $('#' + templateId).html(); // Get the content of the template
$('#modalBody').html(templateContent); // Inject content into the modal body
$('#modalTitle').text(title); // Set the modal title

$('#modalBody .select2normalWithouClear').select2({
placeholder: $(this).data('placeholder')
});

$('.edu-instituteNameOther').hide();

$('#modal').modal('show'); // Show the modal
}

// Event listener for buttons that trigger the modal with different templates
$(document).on('click', '.openModalBtn', function() {
var templateId = $(this).data('template'); // Get the template to load
var modalTitle = $(this).data('title'); // Get the title for the modal

loadModalContent(templateId, modalTitle);  // Call the function to load the content

//TMCEWoFileUpl("250", "");
});

Код: Выделить всё












Modal Title[/b]

×


@* Modal content will be injected here *@










Year
[i]





Level


Option1
Option2
Option3









Institution Name


Other
Option1
Option2
Option3











[/i] Add



[i][/i] Update





Подробнее здесь: https://stackoverflow.com/questions/791 ... e-it-opens
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Jquery»