I implemented a solution using a function that filters a combobox (<select>) based on custom data- attributes. This solution supports:
- Having an
<option> to show when the filter would leave the select empty. - Respects existing selected attributes.
<option> elements without the data-filter attribute are left untouched.
Tested with jQuery 2.1.4 and Firefox, Chrome, Safari and IE 10+.
This is the example HTML:
<select id="myCombobox"> <option data-filter="1" value="AAA">Option 1</option> <option data-filter="1" value="BBB">Option 2</option> <option data-filter="2" value="CCC">Option 3</option> <option data-filter="2" value="DDD">Option 4</option> <option data-filter="3" value="EEE">Option 5</option> <option data-filter="3" value="FFF">Option 6</option> <option data-filter-emptyvalue disabled>No Options</option> </select>
The jQuery code for the filtering:
function filterCombobox(selectObject, filterValue, autoSelect) { var fullData = selectObject.data("filterdata-values"); var emptyValue = selectObject.data("filterdata-emptyvalue"); // Initialize if first time. if (!fullData) { fullData = selectObject.find("option[data-filter]").detach(); selectObject.data("filterdata-values", fullData); emptyValue = selectObject.find("option[data-filter-emptyvalue]").detach(); selectObject.data("filterdata-emptyvalue", emptyValue); selectObject.addClass("filtered"); } else { // Remove elements from DOM selectObject.find("option[data-filter]").remove(); selectObject.find("option[data-filter-emptyvalue]").remove(); } // Get filtered elements. var toEnable = fullData.filter("option[data-filter][data-filter='" + filterValue + "']"); // Attach elements to DOM selectObject.append(toEnable); // If toEnable is empty, show empty option. if (toEnable.length == 0) { selectObject.append(emptyValue); } // Select First Occurrence if (autoSelect) { var obj = selectObject.find("option[selected]"); selectObject.val(obj.length == 0 ? toEnable.val() : obj.val()); } }
To use it, you just call the function with the value you want to keep.
filterCombobox($("#myCombobox"), 2, true);
Then the resulting select will be:
<select id="myCombobox"> <option data-filter="2" value="CCC">Option 3</option> <option data-filter="2" value="DDD">Option 4</option> </select>
The original elements are stored by the data() function, so subsequent calls will add and remove the correct elements.