I have a view and a loop within which a partial view is rendered. With the partial view I have a multi select listbox. So based on count of a item in the loop there could (n) number of listboxes.
My goal is to get all the selected items if any from the first listbox and pre-select them in the remainder of the listboxes. I am not trying to append to the remaining listboxes but just whatever is selected in the first, i would select in the remaining. all the listboxes will have the same items in them.
I am facing diffculty to find the selected indexes or items only from the first one and then i will do the preselection in the remaining, if i could just get the indexes of the selected items in the first one would be helpful. It gives selected items from all the listboxes. please help:
listbox decleration within the partial view
@Html.ListBoxFor(model => model.ServiceTypes,
new MultiSelectList(RunLog.Domain.Lists.GlobalList.PartsServiceTypes(), "ID", "Name"),
new {
style = "width: 200px; height: 80px;",
id = "lstbox",
name = "listbox"
})
button which renders the function
<input id="button" type="button" class="art" onclick="dosomething()" name="broadcast" value="+" />
JS Function:
function broadcast() {
//var element = $('select[multiple]'); This gives me access of all listboxes
// var firstListBoxSelected = $('select[multiple][1] option:selected').text(); t
}
In your example, you gave your listbox the id of “lstbox”. You can use this to find the “list box” using jQuery:
From there, you can modify the code to filter down to just the selected options:
And finally, to get the indexes, we change it again and add just a couple more lines of code:
Or a slightly different approach, taking
:selectedout of your selector and instead manually checking whether the element is selected (might be a hair better in terms of performance):Then you can use
selectedIndicesto pre-select the remaining ones, but first we have to find them:And then change their selected options:
EDIT: Working jsFiddle example
My jsFiddle solution looks like this (I combined the loops so you only have to iterate the select elements once):