我有一个输入字段,它应该由用户填充,只有数字和单点/逗号,并且只能采用以下格式。
这应该发生.on("input")
意味着当用户键入时,它应该确保正确的输入格式。
错误的字符应替换为空白。
格式示例:
1.000
1.281
21212.000
21212.810
没有像这样的:
1.02.12
或
1919,201,00
两个数字块之间只有一个点。
这是我到目前为止所拥有的:正则
表达式 1:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[^0-9]/g,'');
});
正则表达式 2:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
正则表达式 3:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
我想我的replace()
方法有问题。不幸的是,他们都没有像我想要的那样工作。任何帮助表示赞赏。
这是小提琴
应该在 IE11 中工作
你可以试试这个。确保您的输入类型是电话,这将允许您在移动浏览器中使用数字键盘
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句