Can I set the focus on an Anvil component?

Peter asks: When my user is editing a record, I need to check for required fields that are blank when they press a Save button. If a required field is blank, I display an error message, but I would like to then set focus on the TextBox that is blank.

Is it possible to set focus on a TextBox from code?

Hi Peter,

Sure, you can do that. Just call the ā€˜focusā€™ method on the component you want to move the cursor to:

self.text_box_1.focus()

For what itā€™s worth, you can also call self.text_box_1.select() to pre-select the contents of the text box if thereā€™s something the user is likely to want to overwrite.

2 Likes

Think Iā€™m a diff ā€˜Peterā€™ than original poster.

in any case, my ā€˜autofocusā€™ code seems to run in init, butā€¦it doesnā€™t actually seem to work or do anything.

iā€™m hoping that, when the form loads, i can just start typing, and letters will show up in the ā€˜text_box_1ā€™ text box/input. possible?

i donā€™t see any errors in the javascript console.

from anvil import *

class Vocabulary (VocabularyTemplate):
  def __init__(self, **properties):
    # You must call self.init_components() before doing anything else in this function
    #self.text_box_1.focus()
    #self.text_box_1_focus()
    #self.text_box_1_focus()
    self.init_components(**properties)
    #self.text_box_1.focus()
    self.text_box_1_focus()

    # Any code you write here will run when the form opens.
    alert("Good job!")
    self.text_box_1_focus()
    self.text_box_1.text = 'hi'
    self.text_box_1_focus()

Url:
https://R24LJV2CVDIJSJOJ.anvilapp.net/J4KO4OKZGH74H6CE3XQW43OT

Copy app:
https://anvil.works/ide#clone:R24LJV2CVDIJSJOJ=ZATSBHRV3POUDQ6SNDHI5HEC

Hi
try moving the focus code to the ā€œon showā€ event, rather than in ā€œinitā€.

The form is not guaranteed to be active during init.

1 Like

got it work, thanks!

that throws you into the code editor, where you can add the ā€˜self.text_box_1.focus()ā€™ event:

  def text_box_1_show (self, **event_args):
    # This method is called when the TextBox is shown on the screen
    #self.text_box_1_focus()
    self.text_box_1.focus()
    pass

p.s. happy christmas, merry holidays, etc.

2 Likes

Can I set the focus on any component? I canā€™t seem to set it on my button ā€“ the ā€˜focus()ā€™ method does not show up in the list of available options.

My goal is to be able to basically take this ā€˜vocabulary quizā€™ without really taking my hands off the keyboard.

i can Tab and then the button gets highlighted/focused, and then i can hit Enter or and iā€™m all good, but ideally iā€™d like to not have to hit that initial Tab key.

iā€™m open to hacks ā€“ maybe I can send a Tab keystroke? I also saw the keyboard capture/trapper posted by another user. donā€™t know if it works, and iā€™m not on a paid account yet, but open to checking that out.

3 Likes