How to Programmatically Open the Anvil Extras Autocomplete Dropdown on App Load

Hi everyone,

I’ve been loving the flexibility of Anvil and have been using the fantastic Anvil Extras package, which has taken my projects to the next level—huge thanks to the community members who have worked on it!

I’m currently working with the Autocomplete component and am looking to enhance its user experience. Specifically, I’d like to programmatically open its dropdown when the app loads. The goal is to make it immediately clear to users that this is an interactive dropdown. While the component works beautifully, one small challenge is that it isn’t always obvious that it’s a dropdown until the user clicks on it.

The idea is to simulate a click event (or similar action) during the app’s initialization, so the dropdown contents are displayed automatically when the app loads. I haven’t found a straightforward way to do this in Python and am considering diving into JavaScript to identify the component and trigger a simulated click.

Before I do that, I wanted to ask here to see if anyone has tips, tricks, or guidance for accomplishing this. Maybe there’s a more straightforward or native way to handle this that I’ve missed?

I’d be grateful for any insights, whether from the Anvil team or other community members.

Thanks so much in advance!

Richard

I managed to solve this using JS, see below. Would be cool to know if there in a more native way to do it though!

from anvil.js.window import document, setTimeout

class Main_form(Main_formTemplate):
  def __init__(self, **properties):
    self.init_components(**properties)
    ...
    self.form_show()
  def form_show(self, **event_args):
      """Wait for the autocomplete to render and simulate a click."""
      def open_dropdown():
          element = document.querySelector('input.form-control.to-disable.anvil-text-box.anvil-component')
          if element:
              element.focus()
              print("Autocomplete dropdown clicked.")
          else:
              print("Autocomplete component not found. Retrying...")
  
      setTimeout(open_dropdown, 100)  # Wait 100ms
2 Likes