Nahuel Trucco
Nahuel Trucco

Reputation: 21

Switch focus between TextFields on hitting Enter

I need pressing Enter on a MaterialUI TextField to shift focus to the underlying field. That is, I need it to behave similarly to the Tab key operation.

<TextField
    label='Documento'
    name="document"
    autoComplete="document"
    autoFocus
    type='text'
    value={data.document}
    onChange={e => { handleChange(e) }}
    inputProps={{ onKeyDown: handleKeyDown }}
/>

<TextField
    label="Contraseña"
    type="password"
    autoComplete="current-password"
    inputProps={{ onKeyDown: handleKeyDown }}
    onChange={e => { handleChange(e) }}
/>

Upvotes: 1

Views: 47

Answers (2)

Nahuel Trucco
Nahuel Trucco

Reputation: 21

Actually, at the time I forgot to clarify that I am working with React.js. Apologies to whoever took the trouble to reply, and thank you @bystrom.

I finally solved this by implementing React's useRef.

const passFieldRef = useRef(null);

.

<TextField
    id="document"
    label='Identificación'
    name="document"
    value={data.document || ''}
    onChange={handleChange}
    inputProps={{ onKeyDown: handleKeyDown }}
/>

<TextField
    name="password"
    label="Contraseña"
    type="password"
    id="password"
    inputProps={{
        onKeyDown: handleKeyDown,
        ref: passFieldRef
    }}
    value={data.password || ''}
    onChange={e => { handleChange(e) }}
/>

Lastly, this is how handleKeyDown was defined, note that the focus change only applies if ENTER is pressed with focus on a particular field (document). For the rest, other logic is simply executed.

const handleKeyDown = (e) => {
    const fieldName = e.target.name;

    if (e.code === "Enter") {
        switch (fieldName) {
            case 'document':
                passFieldRef.current.focus();
                break;
            default:
                signIn();
                break;
        }
    }
}

Upvotes: 1

bystrom
bystrom

Reputation: 11

A quick solution would be to assign an id to the underlying text field. For example:

<TextField
    label="Contraseña"
    type="password"
    autoComplete="current-password"
    inputProps={{ onKeyDown: handleKeyDown }}
    onChange={e => { handleChange(e) }}
    id="text-field-password"
/>

Then when defining the handleKeyDown function you could check if enter is pressed by checking if the event that triggered the function to execute have a key code of 13. Then, if enter was pressed you could access the underlying text field by the id you gave it and use the focus method on the text field. This will change the keyboard focus from the first text field to the second. Similar to the tab key operation. An example of handleKeyDown function:

function handleKeyDown(e) {
    if(e.keyCode === 13){
      document.getElementById("text-field-password").focus()
    }

  }

If an handleKeyDown function already is defined you could just put the if statement in that function.

Upvotes: 1

Related Questions