How to change the behavior of the filter function of ui.select #5712
-
First Check
Example Codefrom nicegui import ui
ui.select(label="test", options=["a_service", "b_service", "c_service", "service"])
ui.run()DescriptionCurrently when typing on a ui.select the values of the options are filtered, but the filter organizes the results in an alphabetic order. In some cases this is not very convenient because you could type a full matching value, and still have to scroll through the options that contain that value, but are not a full match. In the example above, typing NiceGUI Version3.0.2 Python Version3.10.15 BrowserChrome Operating SystemLinux Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi @gtato, This is a bit tricky, because the filter function is implemented in JavaScript and not meant to be replaced: But with some custom JavaScript we can monkey patch it: @ui.page('/')
def main_page():
select = ui.select(['a_service', 'b_service', 'c_service', 'service'], with_input=True)
ui.run_javascript(f'''
const select = getElement({select.id});
select.findFilteredOptions = function() {{
const needle = this.$el.querySelector("input[type=search]")?.value.toLocaleLowerCase();
return this.initialOptions.filter((v) => String(v.label).toLocaleLowerCase().startsWith(needle));
}}
''')As a simple example, this function uses |
Beta Was this translation helpful? Give feedback.
Hi @gtato,
This is a bit tricky, because the filter function is implemented in JavaScript and not meant to be replaced:
https://github.com/evnchn/nicegui/blob/230983fd92b5eb0183653b8e1a69351a4d8fb123/nicegui/elements/select.js#L26-L32
But with some custom JavaScript we can monkey patch it: