在下面的代码中,文本框在起始位置限制为零。但我想在第一个位置只允许一个零但不超过一个。这是例子
例如:- 0.1012400==> 正确
000.4545000==>不正确
0154==>正确
00154 ==> 不正确
$('input#abc').keypress(function(e){
if (this.selectionStart == 0 && (e.which == 48 || e.which == 46 )){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
最佳答案
您可以简单地测试开头是否有 2 个连续的零,如果是,则删除一个:
$('input#abc').on('keypress keydown keyup',function(e){
var v = $(this).val();
if(v.length >=2 && v[0]=='0' && v[1]=='0') {
$(this).val(v.substring(1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
更新
如果你想在开始时考虑减号,这里有一段代码:
$('input#abc').on('keypress keydown keyup', function(e) {
var v = $(this).val();
if (v.length >= 2 && v[0] == '0' && v[1] == '0') {
$(this).val(v.substring(1));
} else if (v.length >= 3 && v[0] == '-' && v[1] == '0' && v[2] == '0') {
$(this).val('-' + v.substring(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
关于javascript - 如何在第二个位置限制零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48517098/