繁体   English   中英

输入框只接受 0 和 1

[英]Accept only 0 and 1 in input field

我只想在输入字段中接受01在每 4 位数字后添加空格。 通过以下我可以添加空格,但它接受所有数字。 如何将其限制为仅 0 和 1 而不是所有数字? 我在模式上遇到困难。

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

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

你可以试试这个:

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

我想在输入字段中只接受01在每 4 位数字后添加空格。 使用以下内容,我可以添加空格,但它接受所有数字。 如何将其限制为仅 0 和 1 而不是所有数字? 我在模式上有困难。

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

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

暂无
暂无

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

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