I’m trying to move the focus to the next input field when they reach their max length. (I’ve heard this called ‘autotabbing’ elsewhere on various stackoverflow pages.)
I’m using dash-bootstrap-components (dbc), but I assume that will not really change the answer vs dcc
The input fields are generated with:
import dash
from dash import dcc, html, dash_table, Input, Output, State, MATCH, ALL
import dash_bootstrap_components as dbc
from app.data_operations import *
app = dash.Dash()
app.layout = html.Div(
dbc.Row(
children=[
dbc.Col(dbc.Input(id={'identifier': 'form', 'element_id': i}, placeholder='A',
type='text', size="lg", maxlength=1, value='')) for i in range(5)
],
justify='between',
),
)
So far I’ve tried:
Is there a Dash / Python solution here?
Or some kind of external script I can add here?
(I’m a real javascript novice, so don't really know how I’d go about writing the functions for that)
This is indeed possible, but the difficulty for me was deferring the javascript execution. pip install dash_defer_js_import does the trick.
My folder structure looks like this:
Project/
|-- app.py
|-- assets/
| |-- script.js
Any viable content in assets is loaded automatically by Dash, but since the script needs to be deferred, it needs to be ignored when creating the app. (You'd think you can put the script somewhere else but I can't get it to run otherwise for some reason.)
Apart from them that, I just give the element a class name to identify it by. The complete content of app.py looks like this:
import dash
import dash_bootstrap_components as dbc
import dash_defer_js_import as dji
from dash import html
app = dash.Dash(__name__, assets_ignore='script.js')
app.layout = html.Div([
dbc.Row(
children=[
dbc.Col(dbc.Input(id={'identifier': 'form', 'element_id': i}, placeholder='A', className="focus-next",
type='text', size="lg", maxlength=1, value='')) for i in range(5)
],
justify='between',
),
dji.Import(src='assets/script.js')
])
app.run_server()
In the script, I gather all the elements with the designated class name focus-next and add an event listener that checks if the length of its value equals its maxlength attribute. If yes, focus the next focus-next element in line. Content of assets/script.js:
const inputs = document.querySelectorAll('.focus-next')
for (let i = 0; i < inputs.length - 1; i++) {
inputs[i].addEventListener('input', () => {
if (String(inputs[i].value).length === parseInt(inputs[i].getAttribute('maxlength')))
inputs[i + 1].focus()
})
}