Select2 - 占位符不显示

时间:2016-06-04 14:22:37

标签: javascript jquery asp.net asp.net-mvc select2

我在我的asp.net mvc 5应用程序中使用Select2插件。根据{{​​3}}

  

如果您需要更多灵活性,占位符选项允许您传入数据对象而不仅仅是字符串。数据对象的id应与占位符选项的值匹配。

我已经做到了,但占位符仍然没有出现。

代码:

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

有人能告诉我我在这里做错了吗?

4 个答案:

答案 0 :(得分:4)

我认为占位符是一个字符串。不是一个对象 https://select2.github.io/examples.html#placeholders

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

})

答案 1 :(得分:1)

错误是@Html.EditorFor(model => model.AmountDecimal, new { htmlAttributes = new { @class = "form-control", @Value = "100", @readonly = "readonly"} }) 。应该是 -

placeholder: "Select an Title"

https://select2.org/placeholders

答案 2 :(得分:1)

我在这里写是因为我花了很多时间弄清楚代码中的错误。 我的占位符 object 也没有显示(而占位符 string 正确显示了)。关键是空选项元素需要将该值与占位符ID匹配。 我的意思是,如果您输入第一个空选项,如下所示:

<option></option>

它将与声明为的占位符不匹配

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

,它不会显示任何内容。 相反,您应该写:

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

答案 3 :(得分:0)

请注意,如果使用多选,则select2似乎需要将占位符作为对象。有关使用yadcf的一般示例,请参见https://codepen.io/louking/pen/BGMvRP?#(很抱歉,因为额外的复杂性,但是我相信yadcf将select_type_options直接传递给select2)。 (以下摘录)

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