jquery 如何在每两个数字之间添加空格?

lnxxn5zx  于 2023-05-22  发布在  jQuery
关注(0)|答案(2)|浏览(142)

我有3个输入字段,当我在字段中写入时,如何使用输入的ID在每2个数字之间添加空格,在JavaScript中?任何帮助请!

<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" />

我正在尝试这个脚本,但它不适用于所有的输入

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;
        }, "");
zour9fqk

zour9fqk1#

您将无法在<input type="number">中添加空格。根据您的示例判断,指定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">
qyswt5oh

qyswt5oh2#

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

相关问题