In my view I have a code like
<div id="DDLs">
<p>Begin: @Html.DropDownListFor(model => model.ItemID, Model.items, new { @id = "list1" })</p>
</div>
...
<script type="text/javascript">
$(document).ready(function () {
$("#list1").change(function () {
var countrySelected = $("select option:selected").first().text();
$.get('@Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>
That works as expected.The problem is when I add another dropdownlistfor like this:
<div id="DDLs">
<p>Begin: @Html.DropDownListFor(model => model.ItemID, Model.items, new { @id = "list1" })</p>
<p>Options: @Html.DropDownListFor(model => model.Option, @ViewBag.Options as SelectList, new { @id = "list2"})</p>
</div>
After adding it, change event is sometimes fired with selected value of the added dropdownlist, not the one that I expect it would. I have no idea why.
Edit: Thanks to dansasu11 answer, I've figuired out that the problem was in line:
var countrySelected = $("select option:selected").first().text();
I changed it to:
var countrySelected = $(this).val();
Now everything works - of ocurse insted of reciving Text of selected item I'm getting its value, which is also fine.
Perhaps I should have spent more time learning jQuery.
try
<script type="text/javascript">
$(document).ready(function () {
$("#list1").change(function () {
var countrySelected = $(this).find("option:selected").text();
$.get('@Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>
or if you want to be able to select any of the dropdown and get the selected option then change to
<script type="text/javascript">
$(document).ready(function () {
$("select").change(function () {
var countrySelected = $(this).find("option:selected").text();
$.get('@Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>