简体   繁体   中英

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.

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'
    });
});

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
});

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