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