I am trying to attach the same jQuery and JSON ASP.NET MVC3 Method to two different <select> elements:
<select id="StartYear">
<option value="">Select Year</option>
<option value="2000">2000</option>
<option value="2001">2001</option>
</select>
<select id="StartMonth">
<option value="">Select Month</option>
</select>
Same applies for <select> elements with ids "EndYear" and "EndMonth".
I want to attach to both "Start Year" and "End Year" the same jQuery function:
$('[id$="Year"]').change(function () {
var selectedYear = $(this).val();
var selectedId = $(this).attr('id')
if (selectedYear != null && selectedYear != '') {
$.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
var monthsSelect = $('#StartMonth');
if (selectedId == 'EndYear') {
monthsSelect = $('#EndMonth');
}
monthsSelect.empty();
daysSelect.prepend("<option text='-- select month --' value='' selected='selected'></option>");
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text
}));
});
});
}
});
However, this code does not work. I debugged it with Bugzilla and I found out that this condition (selectedId == 'EndYear') breaks the function. The variable selectedId is in the closure scope but I don't know how to bring it inside the function scope. Otherwise I don't know what it cna be the cause.
Keep in mind that without that condition the code was working (of course just with #StartMonth)
console.log($(this).attr('id'));after the assignment? )