1

I have 3 input field,when i write in the field, how to add space between every 2 number using the ID of the input, in javascript? Any help please!

<input type="number" class="phone" placeholder="Phone" id="phone" />
<input type="number" class="phone" placeholder="Second Number" id="secondnumber" />
<input type="number" class="phone" placeholder="Fax" id="fax" />

i'm trying this script, but it's not apply for all the input

const input = document.getElementById("phone") || document.getElementById("secondnumber") || document.getElementById("secondnumber");
        
        input.addEventListener("input", () => input.value = formatNumber(input.value.replaceAll(" ", "")));
        const formatNumber = (number) => number.split("").reduce((seed, next, index) => {
        if (index !== 0 && !(index % 2)) seed += " ";
        return seed + next;
        }, "");
Imy Imy
  • 13
  • 3
  • What you are trying to do is called _input masking_. [Here is a good answer about this](https://stackoverflow.com/a/40514317/5784924). – Nicolas May 17 '23 at 15:45

2 Answers2

0

console.log(("123456789abcdefgh".match(/.{1,2}/g) || []).join(" "))
0

You will not be able to add a space in <input type="number">. Judging by your example, it would be more appropriate to specify type="tel":

document.querySelectorAll('.phone').forEach(el => {
  el.oninput = () => el.value = el.value.replace(/\D/g, '').replace(/(.{2})/g, '$1 ');
})
<input type="tel" class="phone" placeholder="Phone" id="phone">
<input type="tel" class="phone" placeholder="Second Number" id="secondnumber">
<input type="tel" class="phone" placeholder="Fax" id="fax">
imhvost
  • 4,750
  • 2
  • 8
  • 10
  • thank's, but i wanna using the ID of the input – Imy Imy May 17 '23 at 16:15
  • `phone.oninput = () => phone.value = phone.value.replace(/\D/g, '').replace(/(.{2})/g, '$1 ')` [codepen](https://codepen.io/imhvost/pen/dyggOOE) – imhvost May 17 '23 at 18:34
  • I have provided you with a one-size-fits-all solution. You can find the desired item by any means, such as `document.getElementById()`, or as in the above comment – imhvost May 17 '23 at 18:43
  • I was glad to help. If the answer suits you, then please accept it. – imhvost May 18 '23 at 10:14