简体   繁体   English

select2显示第一个选项而不是占位符

[英]select2 shows first option instead of placeholder

I have this in my .cshtml 我的.cshtml中有这个

@Html.DropDownListFor(m => m.Attendance.Time02InId, new SelectList(Model.ClockingLocations, "Id", "Name"), new {@class = "form-control select2-allow-clear"})

Model.ClockingLocations = List of Clock Model.ClockingLocations = Clock列表

public class Clock
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Here's my jquery on document ready 这是我关于文档准备好的jQuery

    var placeholder = "Select...";

    $(".select2-allow-clear").prepend("<option></option>");

    $(".select2-allow-clear").select2({
        allowClear: true,
        placeholder: placeholder,
        width: null
    });

However, my select list still shows the first item of my Model.ClockingLocations when m.Attendance.Time02InId has no value, instead of my placeholder. 但是,当m.Attendance.Time02InId没有值而不是占位符时,我的选择列表仍显示Model.ClockingLocations的第一项。

Try updating your JQuery code 尝试更新您的JQuery代码

var placeholder = "Select...";

$(".select2-allow-clear").prepend("<option></option>");

$(".select2-allow-clear").select2({
    allowClear: true,
    placeholder: placeholder,
    width: null
});

with

var placeholder = "Select...";

$(".select2-allow-clear").prepend("<option value='' selected='selected'></option>");

$(".select2-allow-clear").select2({
    allowClear: true,
    placeholder: placeholder,
    width: null
});

You can also try replacing 您也可以尝试更换

$(".select2-allow-clear").prepend("<option></option>");

with

$(".select2-allow-clear").prepend("<option value=''></option>").val('');

Hope this helps you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM