Reputation:
I have two selects on my page, which are populated on the server.
The top select here is the "master" select which filters the options you can select in the bottom select, by applying the hidden
attribute to the invalid option.
So for instance, this bottom select has, say, 50 options, but only 3 of them apply to "Tyler's Insurance" (see picture below). So the invalid options are hidden. Occasionally, however, when marking many as hidden, the select options will collapse like so, showing only one option with a tiny scrollbar on the right. Clicking the arrows scrolls the option list up and down as expected - and all the other options are there. This only happens on occasion.
Here is the change function that does this logic;
$(top).change(function () {
//First, we make all options invisible.
$(bottom).find('option').prop("hidden", true);
//Then, if the selected option in the top select's ID is the same as the
//stored one on the bottom option, we unhide the option.
$(bottom).find('option[data-id="' + this.selectedOptions[0].dataset.id + '"]').prop("hidden", false);
}
My question is if there is a way to prevent the options that are visible from collapsing into this single-row box, and if so, how would I go about doing so?
Additional information:
Nothing else changes either select, no other selects appear to have this problem.
We target Google Chrome, Version 63.0.3239.84 (Official Build) (64-bit). We utilize jQuery 2.1.4, and Bootstrap 3.3.0.
Trying on the newest Firefox 57.0.2 (64-bit) does not seem to have this error, so I believe it is an issue with how Chrome displays selects...
Upvotes: 1
Views: 247
Reputation:
The solution I came up with;
$(top).change(function () {
//First, we remove all options.
$(bottom).empty()
//Declaring variables here, for clarity; I'd inline them normally.
//The selected option:
var selectedID = this.selectedOptions[0].dataset.id;
//filtered options
var options = $($("#OptionListTemplate").html())
.filter(function (obj) { return $(this).data("top-id") == selectedID });
//simply append the filtered options to the select.
$(bottom).append(options);
}
And the required markup;
<template id="OptionListTemplate">
<option data-top-id="0">Select an option</option>
<!--- Populated by controller, more options would go here.-->
</template>
Instead of using hidden properties or styles, I utilize a template to store all possible values in the page, and just filter out the ones I don't need. This properly resolves the display issue.
Upvotes: 1