Search code examples
vbadatabasevalidationms-access-2016

Return focus to placeholder in text box


I have a login form. I have a username and password text box with a login and close button.

I would like:

  • Text saying "username" in the username and "password" in the pass field.
  • When clicked on the text disappears.
  • If clicked on and you focus on something else without typing anything, it will return back to the placeholder.

I tried this:

Private Sub Form_Load()
txt_username.Value = "Username"
txt_password.Value = "Password"
End Sub

Private Sub txt_username_Click()
If txt_username.Value = "Username" Then
txt_username.Value = ""
End If
End Sub

Private Sub txt_username_LostFocus()
If txt_username.Value = "" Then
txt_username.Value = "Username"
End If
End Sub

My issue is when a change is made, i.e. you type something, then delete it, after you do something else the placeholder doesn't return. Typing breaks my code.


Solution

  • You were close. Try using "GotFocus" instead of "Click":

    Option Explicit
    
    Private Sub Form_Load()
       txt_username.Text = "Username"
       txt_password.Text = "Password"
    End Sub
    
    Private Sub txt_username_GotFocus()
       If Trim(txt_username.Text) = "Username" Then
          txt_username.Text = ""
       End If
    End Sub
    
    Private Sub txt_username_LostFocus()
       If Trim(txt_username.Text) = "" Then
          txt_username.Text = "Username"
       End If
    End Sub