diff --git a/js/ui/select.js b/js/ui/select.js new file mode 100644 index 0000000000000000000000000000000000000000..5de606ff1e3ce635f6085944c848a075864f1c9b --- /dev/null +++ b/js/ui/select.js @@ -0,0 +1,41 @@ +/** + * Creates a new dropdown with available and unavailable options. + * @param {Array<{value: string, name: string}>} options A list of options to display, where `value` sets the property and `name` is displayed. + * @param {string} selected The property to change upon selection. + * @param {function():void} [onchange] Any custom function to run upon selection. + * @param {Object} [object] Any object `property` belongs to, if not the default `V`. + * + * @returns {HTMLSelectElement} + */ +App.UI.DOM.makeSelect = function(options, selected, onchange, object = V) { + const select = document.createElement("select"); + let matchFound = false; + + for (const choice of options) { + const option = document.createElement("option"); + + option.text = choice.name; + option.value = choice.value; + + if (object[selected] === choice.value) { + option.selected = true; + matchFound = true; + } + + select.append(option); + } + + if (!matchFound) { + select.selectedIndex = -1; + } + + select.onchange = () => { + object[selected] = select.options[select.selectedIndex].value; + + if (onchange) { + onchange(); + } + }; + + return select; +}; diff --git a/src/js/slaveListing.js b/src/js/slaveListing.js index d7d7019efcf6a689e4e814ce9a159b9f8e484aeb..b8809b420e4f32bab016593c5a7a28d8f927b72d 100644 --- a/src/js/slaveListing.js +++ b/src/js/slaveListing.js @@ -548,21 +548,11 @@ App.UI.SlaveList.sortingLinks = function(passage) { let span = App.UI.DOM.makeElement("span", "Sort by: "); let order = ["devotion", "trust", "name", "assignment", "seniority", "actualAge", "visualAge", "physicalAge", "weeklyIncome", "health", "weight", "muscles", "intelligence", "sexDrive", "pregnancy", "prestige"]; - const select = App.UI.DOM.appendNewElement("select", span); - - for (const so of order) { - const choice = App.UI.DOM.appendNewElement("option", select, textify(so)); - choice.value = so; - if (V.sortSlavesBy === so) { - choice.selected = true; - } - } + const orderMap = order.map(so => { + return {value: so, name: textify(so)}; + }); - select.onchange = () => { - V.sortSlavesBy = select.options[select.selectedIndex].value; - App.UI.reload(); - }; - div.append(span); + div.append(App.UI.DOM.makeSelect(orderMap, 'sortSlavesBy', App.UI.reload)); span = App.UI.DOM.makeElement("span", " Sort direction: "); order = ["descending", "ascending"];