Input number validation - Restrict to enter only numbers or digits, int amp; float both(输入数字验证 - 仅限输入数字或数字,int amp;两者都浮动)
问题描述
如何限制输入字段只输入数字/数字 int 和 float 两者.有时我们需要为金额等字段同时允许整数和浮点值,因此在这种情况下需要验证.没有可用的解决方案,但它们的代码很大.所以需要一个简短但有效的代码.
How to restrict the input field to enter only numbers/digits int and float both. Sometimes we need to allow both integer as well as float value for fields like amount, so in that case the validation is required. There are no of solutions available but they are of large size code. So need a short but effective code.
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
推荐答案
号码输入限制不需要长代码,试试这个代码.
No need for the long code for number input restriction just try this code.
它也接受有效的 int &浮动两个值.
It also accepts valid int & float both values.
Javascript 方法
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
更新
以上答案适用于最常见的用例 - 将输入验证为数字.
The above answers are for most common use case - validating input as a number.
但根据评论,有些人希望允许一些特殊情况,例如负数和之前向用户显示无效的击键删除它,所以下面是这种特殊用例的代码片段.
But as per comments, some wants to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
这篇关于输入数字验证 - 仅限输入数字或数字,int &两者都浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:输入数字验证 - 仅限输入数字或数字,int &两者都浮动


基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01