0

Iam using MVC4, initially my dropdown displays the list of data, My javascript looks like,

  $.each(data, function (value, key) {
            var opt = "<option value=\"" + key + "\">" + value + "</option>";
            $("#OwnerAgency").append(opt);
            });

How do i set the selected default to be the blank option.

html:

  <div class="SmallTopSpace">
        <span class="LabelNormal">Primary Case Agency</span>
        @Html.DropDownListFor(m => m.Agencies.AgencyKey, new SelectList(""), "", new { @class = "ImportDropDownMax", @id = "OwnerAgency", @onchange = "OwnerAgencyFunction();" })
    </div>
Ravi Shankar
  • 19
  • 1
  • 4

4 Answers4

1

before the $.each just append at that start of the data array another empty element .

or in your html do :

<select>
    <option disabled selected></option>
</select>
jony89
  • 5,155
  • 3
  • 30
  • 40
  • could you please tell me how to append it inside the code? FYI: Posted my html code. – Ravi Shankar Jul 16 '15 at 11:11
  • if you are using DropDownListFor, just create an empty element inline, see : http://stackoverflow.com/questions/7229626/dropdownlistfor-default-value – jony89 Jul 16 '15 at 11:19
0

Can't you just insert an empty option at the top in your view/html?

<select id="OwnerAgency">
  <option></option>
</select> 

Or you can add it in javascript.

 var emptyOption = true;
 $.each(data, function (value, key) {
        var opt;            
        if (emptyOption) {
            opt = "<option></optino>";    
            $("#OwnerAgency").append(opt);
            emptyOption = false;
        }
        opt = "<option value=\"" + key + "\">" + value + "</option>";
        $("#OwnerAgency").append(opt);
        });
Jesper Højer
  • 2,942
  • 1
  • 16
  • 26
0
<select id="mySelect">

</select>

script:

  var myOptions = {
        val1 : 'text1',
        val2 : 'text2'
    };
    var mySelect = $('#mySelect');
    $.each(myOptions, function(val, text) {
        mySelect.append(
            $('<option></option>').val(val).html(text)
        );
    });
    mySelect.append('<option value=' + myOptions.length + ' selected>default</option>');

set your default select before or after select list generation http://jsfiddle.net/3ns3fj3t/

in your case:

 $.each(data, function (value, key) {
            var opt = "<option value=\"" + key + "\">" + value + "</option>";
            $("#OwnerAgency").append(opt);
            });
$("#OwnerAgency").append('<option value=' + data.length + ' selected>default</option>');
SilentTremor
  • 4,747
  • 2
  • 21
  • 34
0

You could do it in your C# ViewModel by adding an empty element to SelectList object:

var selectList = new SelectList(....);
selectList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
selectList.SelectedIndex = 0;
Andrii Tsok
  • 1,386
  • 1
  • 13
  • 26