Reputation: 324
I have 2 listboxfors. When I make a selection in the first listboxfor I need it to automatically select the corresponding option in subsequent listboxfors. If I select individual items(children) I get the result I need. The issue I am having is if I select both items(children) I am not getting both items selected in the subsequent listboxfors. Below are my listboxfors.
@Html.ListBoxFor(m => m.MajorMultiSelects,
new MultiSelectList(Model.Majors, "Code", "Name"),
new { style = "/*display:block;*/" })
@Html.ListBoxFor(m => m.MultiSelectMajorGpas,
new MultiSelectList(Model.MajorGpas, "Code", "Name"),
new { style = "/*display:block;*/" })
Below is the jquery I am using to make the selections.
$("#MajorMultiSelects").change(function() {
console.log("change");//MultiSelectMajorGpas
if ($('#MajorMultiSelects option:nth-child(1)').is(":selected")) {
console.log("1");
$("#MultiSelectMajorGpas option:eq(0)").prop("selected", true);
$("#MultiSelectMajorGpas option:eq(1)").prop("selected", false);
}
else if ($('#MajorMultiSelects option:nth-child(2)').is(":selected")) {
console.log("2");
$("#MultiSelectMajorGpas option:eq(0)").prop("selected", false);
$("#MultiSelectMajorGpas option:eq(1)").prop("selected", true);
}
//else if ($('#MajorMultiSelects option:nth-child(1)').is(":selected") && $('#MajorMultiSelects option:nth-child(2)').is(":selected")) {//This works opposite of what I need. If both items are not selected in listboxfor 1 then items in listboxfor 2 are both selected which is not what I want.
// console.log("1 & 2");
// $("#MultiSelectMajorGpas option:eq(0)").prop("selected", true);
// $("#MultiSelectMajorGpas option:eq(1)").prop("selected", true);
//}
//else {//This doesn't work at all.
// $("#MultiSelectMajorGpas option:eq(0)").prop("selected", true);
// $("#MultiSelectMajorGpas option:eq(1)").prop("selected", true);
//}
});
My listboxfors look like:
<select multiple id="MajorMultiSelects">
<option value="Criminal Justice">Criminal Justice</option>
<option value="Computer Science">Computer Science</option>
</select>
<select multiple id="MultiSelectMajorGpas">
<option value="4">4</option>
<option value="3.45">3.45</option>
</select>
Upvotes: 0
Views: 41
Reputation: 4401
The .val() of a select returns an array of selected values (in case multiple were selected) so all you need is to assign the value of parent select to the value of child select like this:
$("#MajorMultiSelects").change(function() {
let i = 0;
$(this).find('option').each(function() {
$('#MultiSelectMajorGpas option:eq('+i+')').prop("selected", $(this).is(':selected'));
i++;
});
});
Here is an updated example fiddle.
Upvotes: 1