简体   繁体   中英

How to make drop-down default to blank

When I go to my web page, it has a drop down list with a name already selected. I want that it to default to a blank value every time someone goes to that page. They will need to type in that blank space.

<select asp-for="OwnerId" class="form-control" asp-items="@Model.OwnerList"></select>
<select asp-for="OwnerId" class="form-control" asp-items="@Model.OwnerList"></select>

The way i found to have that empty space in the drop down show first was this:

<select asp-for="OwnerId" class="form-control" asp-items="@Model.OwnerList">
    <option value=""></option>
</select>

Thanks for the help. This was my first post and got help almost immediately, This is html. next time i will know more about how to post properly.

1) Make sure Model.OwnerList first value is an empty value (so it is the default value for the list).

Heres an example of creating an empty SelectListItem to place as your first item in Model.OwnerList

var empty = new SelectListItem() {
    Text = "",
    Value = ""
};

2) Make sure OwnerId doesn't already contain a value

If OwnerId already has a value, it will select the first item it finds in Model.OwnerList that matches that value

Do these two things and you will have an empty selection on load

Use append/prepend or appendTo/prependTo to add new empty option to the beginning or end of the list with jquery.

Make sure to run the script after document loaded:

$(function () {
    $("#OwnerId").prepend('<option></option>').val('');
});

or

$(function () {
    $('<option>', { value: '' }).appendTo($("#OwnerId"));
});

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