I have the following code:
let codeBox1 = document.querySelectorAll(".codeBox1");
let codeBox2 = document.querySelectorAll(".codeBox2");
let codeBox3 = document.querySelectorAll(".codeBox3");
let codeBox4 = document.querySelectorAll(".codeBox4");
let OTPdigits = null;
const setOtpInputValue = () => {
OTPdigits = codeBox1.value + codeBox2.value + codeBox3.value + codeBox4.value;
}
In the past, I was using querySelector
and my code was working as well. But now I have to use querySelectorAll
because I've added another 4-inputs (number type) to the DOM (one for Email OTP and the new one for Phone OTP).
Now I need to make codeBox1
to be either codeBox1[0]
or codeBox1[1]
when I access it inside setOtpInputValue()
method. The logic should be based on visibility. Sinde always one of the OTP inputs is visible.
Any idea how can I handle that?
Use reduce()
to 'combine' the inputs. Use a fallback for the non-visible elements if needed
const allBoxes = [...document.querySelectorAll("input") ] let OTPdigits = allBoxes.reduce( (p, c) => (p + c.value), ''); console.log(OTPdigits)
<input class='codeBox1' type='number'> <input class='codeBox2' type='number' value=5> <input class='codeBox3' type='number' style='display: none'> <input class='codeBox4' type='number'>
If you just need the visible elements, change the selector to:
[ ...document.querySelectorAll("input:not([style='display:none'])") ]
Or use another way to check if the element is visible , so you can add an if
in the reduce:
let OTPdigits = allBoxes.reduce((p, c) =>
(p + (c.offsetParent === null ? '' : c.value))
, '');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.