select2 plugin works fine when not inside a jquery modal dialog

jstuardo picture jstuardo · Jun 6, 2013 · Viewed 20k times · Source

I am using select2 plugin inside a jquery dialog but in does not work. When dropping down, the focus moves to the input control but immediately get out from it,not allowing me to type anything.

This is the HTML:

<div id="asignar_servicio" title="Asignar servicios a usuarios">
    <input type="hidden" class="bigdrop" id="a_per_id" />
</div>

And this is the javascript code:

        $( "#asignar_servicio" ).dialog({
            autoOpen: false,
            height: 500,
            width: 450,
            modal: true,
            buttons: {
                "Cancelar": function () {
                    $('#asignar_servicio').dialog('close');
                }
            }
        });
        $("#a_per_id").select2({
            placeholder: "Busque un funcionario",
            width: 400,
            minimumInputLength: 4,
            ajax: {
                url: "@Url.Action("Search", "Personal")",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        q: term,
                        page_limit: 10,
                    };
                },
                results: function (data, page) {
                    return { results: data.results };
                }
            }
        }).on("change", function (e) {
            var texto = $('lista_personal_text').val().replace(/ /g, '');
            if (texto != '')
                texto += ',';
            texto += e.added.text;

            var ids = $('lista_personal_id').val().replace(/ /g, '');
            if (ids != '')
                ids += ',';
            ids += e.added.id;
        });

I have this same code in other page and it works.

Any help will be appreciated,

thanks Jaime

Answer

Jeremy Knight picture Jeremy Knight · Aug 22, 2013

jstuardo's link is good, but there's a lot to sift through on that page. Here's the code you need:

$.ui.dialog.prototype._allowInteraction = function(e) {
    return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
};

Just add it next to wherever you are setting the select2 drop down.