gpt4 book ai didi

javascript - 禁用零作为 <input> 中的第一个字母

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:01 26 4
gpt4 key购买 nike

下面的代码禁用 0 作为 #foo 中的第一个字符。
但是,您可以通过键入 123 绕过此操作,然后拖动以选择 123 并放置 0。 (或输入 ctrl+a)

有没有办法阻止这种情况?

 $('input#foo').keypress(function(e){ 
if (this.value.length == 0 && e.which == 48 ){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />

最佳答案

我会处理输入、属性更改和粘贴事件。然后使用正则表达式匹配任何以 0 开头的内容,并将当前值替换为减去前导 0 的值。

http://jsfiddle.net/SeanWessell/5qxwpv6h/

$('input ').on('input propertychange paste', function (e) {
var val = $(this).val()
var reg = /^0/gi;
if (val.match(reg)) {
$(this).val(val.replace(reg, ''));
}
});

Kevin 报告的错误修复/根据佳能的建议更新:

http://jsfiddle.net/SeanWessell/5qxwpv6h/2/

$('input').on('input propertychange paste', function (e) {
var reg = /^0+/gi;
if (this.value.match(reg)) {
this.value = this.value.replace(reg, '');
}
});

关于javascript - 禁用零作为 &lt;input&gt; 中的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32614989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com