3

I have a Select2 Multiselect html element. While rendering the placeholder is not displaying, but if I select and remove the item, the placeholder is displaying. I have no idea how to make it work. Please advise.

Initially

enter image description here

While Selection

enter image description here

After removing the items

enter image description here

enter image description here

Code:

@Html.DropDownListFor(m => m.Vendor, new SelectList(Model.Status), "Search Status", new { @id = "advanced-search-lsc-status", @class = "form-control", @multiple = "multiple", data_placeholder = "Select Status" })


$('#advanced-search-status').select2({
            minimumResultsForSearch: -1,
            placeholder: function(){
                $(this).data('placeholder');
            },
            width: '100%'
        });
Ranjith Varatharajan
  • 1,596
  • 1
  • 33
  • 76
  • Not related, but use `ListBoxFor()`and delete the `new { multiple = "multiple" }` - refer [this answer](https://stackoverflow.com/questions/40725358/why-does-the-dropdownlistfor-lose-the-multiple-selection-after-submit-but-the-li/40732481#40732481) –  Apr 04 '18 at 10:22
  • @StephenMuecke, I tried it, still the issue exists :( btw good info – Ranjith Varatharajan Apr 04 '18 at 10:30
  • I did say _Not related_ :) - its was just to fix the other issue with your code –  Apr 04 '18 at 10:35

3 Answers3

6

Just now found out that what was wrong, initially the width was set to 0 which hides the placeholder.

enter image description here

Just manipulated using this jquery code.

.select2-container--default .select2-search--inline .select2-search__field{
    width:initial!important;
}

now it works

enter image description here

Thanks guys.

Ranjith Varatharajan
  • 1,596
  • 1
  • 33
  • 76
4

try this

.select2-container .select2-search--inline:first-child {
    float: none;
}
.select2-container .select2-search--inline:first-child .select2-search__field{
    width: 100% !important;
}
Tengiz G
  • 41
  • 1
  • Using the "first-child" selector assures that the search field doesn't take up extra room when options are selected -- it only maintains its width when the multi-select is empty – lflier Jan 28 '23 at 00:02
1

Simply add attr placeholder

$("#advanced-search-status").attr("placeholder", "Select Status");

or

$('#advanced-search-status').select2({
    placeholder: "Select Status"
});
Parth Raval
  • 4,097
  • 3
  • 23
  • 36