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:

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

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


}

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>
</select>

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

Demo: https://jsbin.com/poxijiluci/edit?html,js,output