I have the following code with two identical lists. Based on the selection on one, I want to hide the same element of other element. I can see that style="display: none;
is getting inserted in <option value="20" style="display: none;">A</option>
when I select A
from left list and expect A
to be hidden in the right list. But it’s not hidden.
Here’s my JSFiddle
1 Like
You could set the disabled
attribute instead:
Otherwise you could use the remove() method to remove an option but restoring an option is then less straightforward.
Thanks. Will it work with the select2()
library as well?
I think it will work with Select2 but I have never used Select2. I have checked that Select2 will handle disabled options (link).
Doesn’t seem to be working when I added select2()
. Here is the updated JSFiddle using your code where I included the select2() library
Using Developer Tools I can see that Select2 replaces the <option>
elements with an arrangement of <span>
elements and reduces the <select>
element to 1 x 1 pixels. So that JavaScript is not going to work.
1 Like
Perhaps I didn’t understand it, the developer tools is still showing me option tags for both available Locations
and destinationLocations
. Are you referring to something else here that won’t let the desired behavior happen?
Does this means that there is no way to hide or achieve what I’m looking for?
Developer Tools is showing the <select>
element has been reduced to only 1 x 1 pixel:
Actually the <option>
elements are still present in the HTML but the options in the drop-down list are rendered using <span>
elements:
I see Section 12 of the Select2 documentation covers programatic control but does not seem to include methods to set or clear disabled attributes or to delete individual options.
$("#availableLocations").select2();
$("#destinationLocations").select2();
$("#availableLocations").on("change", function () {
if($("#destinationLocations").val() == $("#availableLocations").val()) {
$("#destinationLocations").val(-1).trigger("change"); //The current selection is invalid.
}
$("#destinationLocations option").each(function() { this.disabled = false; });
$("#destinationLocations option[value='"+$("#availableLocations").val()+"']")[0].disabled = true;
})
The select2 shell doesnt hide the options, it just shells them.
Thanks. That’s what I was looking for. select2() makes it more difficult to achieve such things I believe.