Mouna Mouna - 24 days ago 7
ASP.NET (C#) Question

Trying to select the value that was chosen in a drop down list using the ID of the drop down list

enter image description hereI am trying to retrieve the value that was selected by the end user in a drop down list. The variable country is always null, I am using the id of the drop down list to retrieve the value that was selected by the user.

Here is the code in my view:

var country = document.getElementById("Countries");
var value = country.options[country.selectedIndex].value;
var text = country.options[country.selectedIndex].text;

@Html.Label("Country", "Country")
<select name="Countries" id="Countries">
@foreach (var country in ViewBag.countries)
<option value="@(">@(</option>


Answer Source

Try like this,

<label for="Country">Country</label> 
<select name="Countries" id="Countries"> 
    <option value="Iceland">Iceland</option> 
    <option value="Kosovo">Kosovo</option>
    <option value="Belgium">Belgium</option>

var element = document.getElementById("Countries"); 
var selected_country_value = element.options[element.selectedIndex].value;