I am trying to have the input fields tab over to the next field once maxlength is met but I keep getting an error Failed to execute 'querySelector' on 'Document': 'name=2' is not a valid selector.. Ive read over mozialla's explanation of a querySelector and I've tried using the elements id to focus() on but that gives the same error. I guess Im not understanding how to properly craft a selector to pass to the querySelector.
My Input fields ill only show 2 i have 3:
<Input
onChange={dateChange("month")}
value={date.month}
id="1"
maxLength={2}
type="number"
/>
<span className="sep">/</span>
<Input
onChange={dateChange("day")}
value={date.day}
name="2"
id="2"
maxLength={2}
type="number"
/>
My onChange:
const dateChange = (field) => (e) => {
const fieldIndex = e.target.name;
let fieldIntIndex = parseInt(fieldIndex, 10);
// format to fit
let value = e.target.value;
if (value.length === e.target.maxLength) {
if (fieldIntIndex < 3) {
const nextfield = document.querySelector(
`name=${fieldIntIndex + 1}`
);
console.log(nextfield);
if (nextfield !== null) {
nextfield.focus();
}
}
}
const d = { ...date, [field]: value };
setDate(d);
debounceCallback(handleDateInputChange, d);
};
Im still learning so any advice on this would be great :) thanks in advance!
First of all, I think that it is incorrect to set event listeners like this:
onChange={dateChange("month")}
If you do it that way, you actually execute that function during rendering of the page. The function should be executed when the event occurs. The correct way to do this would be:
onChange={dateChange}
If you also wanted to add parameters to your function then you should do it like this:
onChange={dateChange.bind(this, "month")}
Moreover, regarding the query selector, I think the correct syntax would be:
const nextfield = document.querySelector(`input[name='${fieldIntIndex + 1}']`);
Your name prop is set to an input element, so we use input[name].
Also name has a string value, so we use input[name=''].
Finally we want to set name value parametrically, so we use `input[name='${parameter}']`.
You can find the MDN documentation of bind JavaScript function here and the documentation of querySelector here.
Edit: Another alternative for navigating among inputs would be the tabindex attribute. You can find more about it here.
Name is a string So i think you should do it like this(add brackets)
name='${fieldIntIndex + 1}'