“How to automatically focus and highlight the text in an input” is a question that gets asked pretty frequently here on the Bubble forums. It’s not something natively handled by Bubble at this time. It’s a useful thing to do, though, because it allows your users to just start typing without having to first clear an input’s initial value.
I just figured out how to do this for my own app and I thought I’d share it here because it’s working so well for me:
-
Step 1: You’ll need to install the Toolkit plugin that allows you to run JavaScript in workflows.
-
Step 2: In your app’s settings on the General tab you’ll need to turn on the “Expose the option to add an ID attribute to HTML elements”
-
Step 3: Add an ID Attribute to your input that you wish to highlight via JavaScript. You can see it here at the very bottom. In this example, I named mine “input-tender-amount” but you can name yours whatever you want:
-
Step 4: Create some workflow that will allow you trigger the JavaScript. In my case, when a particular group was visible I wanted a particular input to be highlighted. The Toolkit plugin makes the “Run javascript” action available to you for workflows as seen here:
The actual JavaScript code to make this work is:
const input = document.getElementById('YOUR_INPUT_ID_GOES_HERE'); input.focus(); input.select();
I have found that this technique does not work if your page or element is not done loading yet so you may need to play around with your conditions about when this JavaScript code fires off.
I hope you found this to be a handy tip! Please let me know if it works for you, too.