Search code examples
javascriptjqueryloopsdrop-down-menuwebgrid

Unable to retrieve selected value in DropDownList in ASP.NET MVC?


Trying to retrieve the selected value of my DropDownList in ASP.NET MVC. I'm using the following code:

HTML

 grid.Column("Other", header: "Other", format: @<text>@Html.DropDownList("OtherKey", (IEnumerable<SelectListItem>)ViewBag.OtherKeysList, new { @class = "extra-class" })</text>)))

Resulting in the following:

enter image description here

Trying to retrieve the selected values of my DropDownList(in this case: otherkey3, otherkey2, otherkey1) with the code below:

 <script type="text/javascript">

       var dict = [];

       $('#btnSubmit').click(function (e) {
           $('#tableID  > tbody  > tr >  td').each(function () {
               $('#OtherKey > option').each(function () {
                   console.log(($(this).val()));
               });
           });
       });

   </script>

However this does not work and I'm getting the following output:

enter image description here

Does anyone see what I'm doing wrong?

Thanks in advance!


Solution

  • There's a couple of issues here. First, you're getting the value of each <option> so it will always return all of the options, selected or otherwise. Use .val() on the <select> itself to get the currently selected value:

    console.log($('#OtherKey').val());
    

    However, it also appears that you're re-using the OtherKey ID in your HTML. Take a look at the actual HTML generated by your server-side code. If IDs are not unique then the behavior of JavaScript code using those IDs is undefined.

    Your elements do appear to be using a class, so you can use that instead. (If it's not unique to those elements then you can assign them an additional class which is.) Something like this:

    $('.extra-class').each(function () {
        console.log(($(this).val()));
    });
    

    Note also that you don't need to loop through the table rows and through the <select> elements, just the latter is fine. Unless you specifically need to identify your table rows for some other reason not shown here.