jQuery Chosen does not show data-placeholder when it is filled

emre nevayeshirazi picture emre nevayeshirazi · Jul 25, 2012 · Viewed 16.3k times · Source

I am using jQuery Chosen plugin in my ASP.NET MVC application. The data-placeholder attribute is not working when the dropdownlist has items in it. Instead of showing default text it automatically selects the first item in the list.

This is how I define my dropdownlist.

@Html.DropDownListFor(m => m.Keep, Model.Data, 
     new { @class = "chzn-select", data_placeholder = "Default..." })

If Model.Data is empty (it is filled in view model using EF), then default text is displayed. Otherwise, the first item is selected. I always want my dropdownlist to show default value.

I apply the plugin via $('.chzn-select').chosen(); Nothing special.

Any ideas ? Thanks in advance.

Answer

Vince Lowe picture Vince Lowe · Jul 25, 2012

You need to add an empty option first.

as per documentation - http://harvesthq.github.com/chosen/

Note: on single selects, the first element is assumed to be selected by the browser. To take advantage of the default text support, you will need to include a blank option as the first element of your select list.

Maybe use jQuery to add it

$(".chzn-select").prepend("<option></option>");