Sascha Lois
Sascha Lois

Reputation: 171

Select2 doesn't show options

I'm currently testing Select2.js in my ASP.NET MVC project.

The first test on a "normal" view just worked fine but now I'm trying to add this to a select box inside a partial view that gets loaded on Ajax Call and then displayed inside a <div> on the normal view page.

The code to generate the dropdown looks like this:

@Html.DropDownList("addRole",
   new SelectList(ViewBag.availableRoles, "Id", "Name"),
   "Rolle auswählen", 
   new { @name="addRole", @class = "form-control" }
)

And on the end of the partial view file I added the following:

$(document).ready(function () {
    //var data = [{ id: 1, text: "Test" }];

    $("#addRole").select2({
        //data: data
    });
});

It looks like it works because of the look of the select box changes but when I try to open it, it just shows nothing. Same happens when I uncomment the data variable code above.

It just doesn't show anything to me and I don't know why.

I've already tried to add the JavaScript code to $(document).ajaxComplete or in the success function from the AJAX call but it doesn't change anything.

Upvotes: 7

Views: 18216

Answers (3)

Dark flame master
Dark flame master

Reputation: 11

I found a solution here: Select2 does not function properly when I use it inside a Bootstrap modal

It says:

This will cause the dropdown to be attached to the modal, rather than the <body> (here modal is the element)

Upvotes: 1

Aurovrata
Aurovrata

Reputation: 2279

In my case, I was displaying a select2 on a pop-up element and this causes the dropdown to disappear because it is attached by default to the <body> element.

Select2 troubleshooting guide highlights a similar issue with Bootstrap modals.

To overcome this problem I had to use the dropdown placement option provided,

let $select = $('select'), 
  $parent = $select.parent();

$select.select2({
  dropdownParent: $parent
});

Upvotes: 8

Sascha Lois
Sascha Lois

Reputation: 171

I got the answer now. The problem was not that the select2 element has no items, the problem was the given items did not show up. So I thought about why didn´t they show up and found out that I´m really stupid. It did show up, but I can´t see it because of the z-index. My popup window got a z-index of 20k so the dropdown list was behind the window.

So to solve this just add:

.select2-dropdown {
    z-index:99999;
}

Or add a dropdownCssClass to the select2 settings with the given z-index like this:

.select2-dropdown.increasezindex {
    z-index:99999;
}

JS:

$(document).ready(function () {
    $("#addRole").select2({
        dropdownCssClass:'increasezindex'
    });
});

Upvotes: 8

Related Questions