简体   繁体   中英

Select2 component is not working correctly

When opening multiple instances of the same modal bootstrap cascading window, the initialization of the select2 component works normally in the last window. In previous windows, the component stops working. To initialize the component, I get the last instance of the modal window and set the dropdownParent property. It should work for all open windows, but it only works for the last one open.

Does anyone know how to solve this problem?

Thanks:)

//get the last instance of the modal window
var lastModal = $('body').children('.generic-modal').last();

//get the select component
var selFormaContatoControleTipo = lastModal.find('.sel-forma-contato-controle-tipo');

//Initialize
selFormaContatoControleTipo.select2({
    tags: "true",
    createTag: function () {
        // Dessabilita a inserção quando Enter for pressionada
        return null;
    },
    placeholder: "Selecione uma opção",
    allowClear: false,
    width: '100%',
    dropdownParent: lastModal,
    language: {
        noResults: function () {
            return "Nenhum resultado encontrado";
        }
    }
});

<div class="col-md-3">
    <label asp-for="FormaContatoControleTipo" class="control-label">Tipo de Controle</label>
    <select asp-for="FormaContatoControleTipo" asp-items="Model.FormasContatosControlesTipos" title="Selecione uma opção" class="form-control sel-forma-contato-controle-tipo" style="position: fixed !important;"><option value=""></option></select>
    <span asp-validation-for="FormaContatoControleTipo" class="text-danger"></span>
</div>

Video:

https://imgur.com/a/v0GM9JH

As I didn't get feedback, I discovered, accidentally, that the problem was due to the select id. The ASP.NET razor creates the id and name automatically, but I was calling the component by the class name '.sel-forma-contato-controle-tipo'... When opening the modal window more than once, automatically, there were identical ids... When initializing the plugin, the other element of the same id was also changed...

$("input:text, input:radio, input:checkbox, select").each(function () {
    var oldId = $(this).attr("id");
    $(this).attr("id", oldId + getQuantityOfGenericModals());
});

The solution was to change the ids of all elements on the page, including the selects. I hope this can help other people with the same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM