简体   繁体   中英

Dynamically add new option to <select> using jQuery?

I have the following code in my MVC5 app which fills several SelectList and then passes them from my Controller via the ViewBag to my View

Controller :

        // GET: INV_Assets/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            INV_Assets iNV_Assets = await db.INV_Assets.FindAsync(id);
            if (iNV_Assets == null)
            {
                return HttpNotFound();
            }

            ViewBag.Location_Id = new SelectList(db.INV_Locations, "Id", "location_dept", iNV_Assets.Location_Id);
            ViewBag.Manufacturer_Id = new SelectList(db.INV_Manufacturers, "Id", "manufacturer_description", iNV_Assets.Manufacturer_Id);
            ViewBag.Model_Id = new SelectList(db.INV_Models, "Id", "model_description", iNV_Assets.Model_Id);
            ViewBag.Status_Id = new SelectList(db.INV_Statuses, "Id", "status_description", iNV_Assets.Status_Id);
            ViewBag.Type_Id = new SelectList(db.INV_Types, "Id", "type_description", iNV_Assets.Type_Id);
            ViewBag.Vendor_Id = new SelectList(db.INV_Vendors, "Id", "vendor_name", iNV_Assets.Vendor_Id);
            return View(iNV_Assets);
        }

View :

@model Tracker.Models.INV_Assets

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">
    $('select.dropdown').append('<option>' + "<<< Add New >>>" + '</option');
</script>


<h3>Edit Asset @Model.Id</h3>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @*@Html.LabelFor(model => model.Model_Id, "Model_Id", htmlAttributes: new { @class = "control-label col-md-2" })*@
            <span class="control-label col-md-2">Model:</span>
            <div class="col-md-10">
                @Html.DropDownList("Model_Id", null, htmlAttributes: new { @class = "form-control dropdown" })
                @Html.ValidationMessageFor(model => model.Model_Id, "", new { @class = "text-danger" })
            </div>
        </div>

.....

This renders the following (just one for example):

<select class="form-control dropdown valid" id="Model_Id" name="Model_Id">     
    <option selected="selected" value="1">XTERAV12</option>
    <option value="2">5330</option>
    <option value="3">Sunblade 6000</option>
    <option value="4">DV7650</option>
    <option value="5">R40</option>
    <option value="6">A1396</option>
    <option value="7">Inspiron 3646</option>
</select>

What I'm attempting to do now is (once the page is ready) use jQuery to add an option for "<<< ADD NEW >>>" at the TOP of each one of my groups.

To try this, I added a class titled "dropdown" to my first @Html.DropDownList() on my view. Then in my script, I'm attempting to select all with the .dropdown class and add the desired . When I refresh my page, nothing happens. However (in Google Chrome) if I use the same code $('select.dropdown').append('<option>' + "<<< Add New >>>" + '</option'); within my Console window, the option is added at the bottom of the list.

Can anyone help with this? Why is it working in the Browser Console but not on load itself?

When the page loads I'm trying to get the "<<< ADD NEW >>>" as the top of each one of the list, and then I want to (on click) popup my Create() View for the relevant list (Location, Manufacturer, etc.)

You need to use the prepend method which will insert the element as the first child, while append insert content after the last child:

The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append() ).

$('select.dropdown').prepend('<option>' + "<<< Add New >>>" + '</option');

Update To use section you should do the following:

In your _Layout.cshtml add this:

@RenderSection("Scripts", false)

In your view use it like this:

@section Scripts 
{
    <script>some script</script>
}

You can place the section wherever you want in the view and it will render in the correct place.

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