Put focus back on Inputs.Select after pressing button

Hi,

I’m using a wrapper function to submit a form, thanks to @mootari, see Submittable Input Forms / Fabian Iwand | Observable

I have two Inputs.Select lists: the first one you select a Category then the second list shows a set of Items for that specific Category. So each time you change Category, the Item list also changes. Below the two lists I have an Inputs.Form with a text box and Submit button.

What I need to do is move the focus back to the “Select Item” list when some text is entered and the Submit button is pressed. I can make it work with document.getElementById(‘’).focus() in the function that runs when the Submit button is pressed.

The problem is that the Id changes when I change the Select Category list, which is the one that controls the Select Item list. How can I focus on something when the Id keeps changing?

See my notebook to reproduce: Focus Back on Select Input / Obs Data App | Observable

You can use a side effect by adding a cell like

values, viewof selectItem.input.focus()

This cell will rerun whenever values changes and then focus the select element.

As an aside, you should not need to use getElementById() in notebooks since you can usually reference elements directly. Another benefit of doing it this way is that you declare an explicit dependency on the referenced element which Observable’s notebook runtime can use to update dependent cells reactively.

Thank you for the fast response. Perfect solution. I still have a lot to learn :grinning:

The viewof prefix might seem a bit magical, but at its core it’s just a macro that causes Observable to produce two variables from the cell:

  • the DOM element that holds the input, which you can still reference by adding viewof before the name
  • an async generator of the element’s value that yields new values every time an input event happens.

If you want to dive a little deeper into the topic you might find this short guide helpful: