Forum Academy Marketplace Showcase Pricing Features

Handy tip: Here's how to highlight input text using JavaScript

“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.

3 Likes

Hi @BrianHenderson - thank you for the tips.
Would you happen to also perhaps know what javascript code would help me achieve a specific styling such as bold or color of a particular regex, for example? My application use is to format “mentions” as bold and blue, I am looking for a way to do this as the user is typing their input.

Hi @alex.yaroshuk I’m sorry but that’s a bit beyond my skill set. You may be best served by making a new topic with this question so that others may find it easier to answer you. This may also be a good question to post on other developer forums elsewhere online because this isn’t just a Bubble question but a more general web dev kind of question.

You might take a cue from the Bubble forum’s way of mentioning someone’s username - they don’t style it differently in the input when you write “@someone’s_name” but it immediately appears as a tag after it’s submitted, plus the @ symbol makes it pretty clear there’s something particular going on here.

1 Like