我只想复制粘贴数字到“数字字段”中。如果我不阻止复制粘贴,则可以在数字字段中复制'e','+','-'
和'.'
。在数字字段中,我可以键入这些字符,因此我使用了另一个脚本。我只想键入和复制粘贴数字。
请检查代码:
jQuery("#otp_number").bind("cut copy paste", function(e) {
e.preventDefault(); //prevent the default behaviour
});
document.querySelector("#otp_number").addEventListener("keypress", function(evt) {
if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57) {
evt.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
OTP: <input type="number" id="otp_number" data-ignorepaste="" />
最佳答案
jQuery("#otp_number").on("paste", function(e) {
if (e.originalEvent.clipboardData.getData('text').match(/[^\d]/))
e.preventDefault(); //prevent the default behaviour
})
.on("keypress", function(e) {
if (e.keyCode != 8 && e.keyCode != 0 && e.keyCode < 48 || e.keyCode > 57)
e.preventDefault();
});
您无需限制复制或剪切操作。对粘贴事件进行测试就足够了。仅当在剪贴板中找到要粘贴的非数字字符时,才阻止该事件。
我没有时间进行测试,因此,请尝试在必要时进行改进。
编辑:
我很惊讶我的原始答案得到了如此多的正面反馈。但是,这是一个替代版本,我认为它更具容忍性和用户友好性。它允许首先输入任何可能的字符(每次输入或粘贴),然后删除所有非数字字符:
jQuery("#otp_number").on("paste keyup",function(e){
$(this).val(this.value.replace(/[^\d]/g,''))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="other" placeholder="anything"><br>
<input type="text" id="otp_number" placeholder="numbers only">