Reputation: 383
Having a changeEvent
on the DropDownListFor
, it does trigger the code for the event, however the selected item is null, i.e. $(this).val();
is null
View:
<script>
$(function () {
$("#selected_listBulletinBoardsMessages").change(function (e) {
var val = $(this).val();
..
});
});
</script>
<div>
<div id="selected_listBulletinBoardsMessages">
@Html.DropDownListFor(model => model.listBulletinBoardsMessages, Model.listBulletinBoardsMessages.Select(b => new SelectListItem() { Value = b.Department, Text = b.Department }), "All Departments", new { @class = "form-control" })
</div>
</div>
What am i doing wrong?
Upvotes: 0
Views: 2074
Reputation: 218798
Because div
elements don't have "values". You want the value of the select
element. Ideally you'd bind to that element's change
event instead:
$("#selected_listBulletinBoardsMessages select").change(function (e) {
var val = $(this).val();
..
});
But if, for reasons outside the context of this question, you want to bind to the div
like you currently are then you can get the value from the select
inside of it. The e
event variable that you already have can get you there. Perhaps something like this:
$("#selected_listBulletinBoardsMessages").change(function (e) {
var val = $(e.target).val();
..
});
Naturally, this would likely need to change if you have more than one select
element inside the div
. Currently that's not the case in the code you're showing, though.
Note also that this is based on the assumption that DropDownListFor()
is indeed generating a select
element. I can't imagine why it wouldn't, but I suppose it's possible. What you're at least going to want to do is examine the actual HTML and see what's there in order to refine any JavaScript code used to access that HTML.
Upvotes: 3
Reputation: 2317
It should be like this
<script>
$(function () {
$("#selected_listBulletinBoardsMessages select").change(function (e) {
var val = $(this).val();
..
});
});
</script>
because you are trying to call div
change event
which should not be there in this case.
Upvotes: 1
Reputation: 133403
div
doesn't have the change
event.
You should listen for change
event of select
, thus specify the ID to DropDownListFor
element.
<div>
@Html.DropDownListFor(model => model.listBulletinBoardsMessages,
Model.listBulletinBoardsMessages.Select(b => new SelectListItem() { Value = b.Department, Text = b.Department }),
"All Departments",
new { @class = "form-control",
id="selected_listBulletinBoardsMessages"
})
</div>
Upvotes: 2