简体   繁体   English

输入框只接受 0 和 1

[英]Accept only 0 and 1 in input field

I want to accept only 0 and 1 in input field and add spaces after every 4 digits.我只想在输入字段中接受01在每 4 位数字后添加空格。 With the following I can add spaces but it accepts all digits.通过以下我可以添加空格,但它接受所有数字。 How can I restrict it to only 0 and 1 instead of all digits?如何将其限制为仅 0 和 1 而不是所有数字? I'm having difficulty in the pattern.我在模式上遇到困难。

document.getElementById('num').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{4})/g, '$1 ').trim();
});

Demo: https://jsfiddle.net/5rvfgpzo/演示: https://jsfiddle.net/5rvfgpzo/

You can try this:你可以试试这个:

 document.getElementById('num').addEventListener('input', function (e) { e.target.value = e.target.value.replace(/[^0-1]/g, '').replace(/(.{4})/g, '$1 ').trim(); });
 input { width: 200px; padding: 5px; }
 <label for="num">num</label> <input id="num" type="text" min="0" max="1" name="num" maxlength="14" />

I want to accept only 0 and 1 in input field and add spaces after every 4 digits.我想在输入字段中只接受01在每 4 位数字后添加空格。 With the following I can add spaces but it accepts all digits.使用以下内容,我可以添加空格,但它接受所有数字。 How can I restrict it to only 0 and 1 instead of all digits?如何将其限制为仅 0 和 1 而不是所有数字? I'm having difficulty in the pattern.我在模式上有困难。

document.getElementById('num').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{4})/g, '$1 ').trim();
});

Demo: https://jsfiddle.net/5rvfgpzo/演示: https://jsfiddle.net/5rvfgpzo/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM