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