英文:
How to add space between every 2 number?
问题
Sure, here's the translated code portion:
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;
}, "");
If you have any more questions or need further assistance, please feel free to ask.
英文:
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;
}, "");
答案1
得分: 0
Sure, here's the translated code snippet:
console.log(("123456789abcdefgh".match(/.{1,2}/g) || []).join(" "))
Please let me know if you need any further assistance.
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log(("123456789abcdefgh".match(/.{1,2}/g) || []).join(" "))
<!-- end snippet -->
答案2
得分: 0
你无法在<input type="number">
中添加空格。根据你的示例,更合适的是指定type="tel"
:
<input type="tel" class="phone" placeholder="电话" id="phone">
<input type="tel" class="phone" placeholder="第二号码" id="secondnumber">
<input type="tel" class="phone" placeholder="传真" id="fax">
你提供的代码片段中已经使用了type="tel"
来定义电话号码输入字段。
英文:
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"
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.querySelectorAll('.phone').forEach(el => {
el.oninput = () => el.value = el.value.replace(/\D/g, '').replace(/(.{2})/g, '$1 ');
})
<!-- language: lang-html -->
<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">
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论