简体   繁体   中英

Select2 — placeholder not displaying

I'm using Select2 Plugin in my asp.net mvc 5 application. according to the documentation

The placeholder option allows you to pass in a data object instead of just a string if you need more flexibility. The id of the data object should match the value of the placeholder option.

I have done exactly that, but the placeholder is still not showing up.

Code:

model.Step6.Titles.Insert(0, new SelectListItem() { Text = "Select a Title", Value = "0", Selected = true });

@Html.DropDownListFor(model => model.Step6.Title, Model.Step6.Titles, new { id="teamtitle", @style = "width: 100%;"})

$("select").select2({
    allowClear: true,
    placeholder: {
        id: "0",
        placeholder: "Select an Title"
    }
})

can someone show me what I'm doing wrong here?

I think placeholder is a string. Not an object https://select2.github.io/examples.html#placeholders

$("select").select2({
    allowClear: true,
    placeholder:"Select an Title"

})

Error is placeholder: "Select an Title" .It should be-

$("select").select2({
    allowClear: true,
    placeholder: {
        id: "0",
        text: "Select an Title" //Should be text not placeholder
    }
})

https://select2.org/placeholders

I write here because I've spent a lot of time figuring out what was wrong in my code. I've got the placeholder object not showing too (whereas a placeholder string shows correctly). The point is that the empty option element needs to match the value to the placeholder id. I mean, if you put a first empty option like the following:

<option></option>

it won't match with a placeholder declared as

placeholder : { id:'0', text:'Please select...'}

and it won't display anything. Instead you should write:

 <option value="0"></option>

Note if multi-select is used select2 seems to require the placeholder as an object. See https://codepen.io/louking/pen/BGMvRP?# for generic examples using yadcf (sorry for the extra complexity, but I believe yadcf passes select_type_options directly to select2). (Excerpt below)

  {
    column_number:2,
    select_type: 'select2',
    filter_type: 'multi_select',
    select_type_options:
      {
        placeholder: {
          id: -1,
          text: 'pick col2'
        },
        width: '200px',
        allowClear: true,
      }
  },

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