有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
这里是一个非常简短的解决方案,不使用已弃用的keyCode或,不阻塞任何非输入键,并使用纯javascript。(在Chromium 70.0.3533, Firefox 62.0和Edge 42.17134.1.0中测试)
HTML:
<input type="text" onkeypress="validate(event)">
JS:
function validate(ev) {
if (!ev) {
ev = window.event;
}
if (!ev.ctrlKey && ev.key.length === 1 && (isNaN(+ev.key) || ev.key === " ")) {
return ev.preventDefault();
}
}
其他回答
一个使用jQuery和replace()而不是查看事件的简短而甜蜜的实现。keyCode或event.which:
$('input.numeric').live('keyup', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
只有一个小的副作用,输入的字母出现暂时和CTRL/CMD + A似乎表现有点奇怪。
对于喜欢说俏皮话的人。
string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
我在输入type="text"上使用这段代码,并使用AngularJS在按键时激活,但如果喜欢,可以使用jQuery。只需将此代码放入一个函数中,该函数以某种方式通过按键激活。
它只允许数字,数字+十进制,数字+十进制+数字。
CODE
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";
testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";
testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";
testFour = "622632463.23464236326324363"
=> "622632463.23";
这是为美国货币构建的,但它可以更改为允许超过两个小数点后的第一个小数,如下所示…
改变了代码
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');
testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";
:)
如果你可以使用插件,这里有一个我测试过的。除了膏体外,效果很好。
数字输入
这里是一个演示http://jsfiddle.net/152sumxu/2
下面的代码(库内粘贴)
<div id="plugInDemo" class="vMarginLarge">
<h4>Demo of the plug-in </h4>
<div id="demoFields" class="marginSmall">
<div class="vMarginSmall">
<div>Any Number</div>
<div>
<input type="text" id="anyNumber" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
// Author: Joshua De Leon - File: numericInput.js - Description: Allows only numeric input in an element. - If you happen upon this code, enjoy it, learn from it, and if possible please credit me: www.transtatic.com
(function(b) {
var c = { allowFloat: false, allowNegative: false};
b.fn.numericInput = function(e) {
var f = b.extend({}, c, e);
var d = f.allowFloat;
var g = f.allowNegative;
this.keypress(function(j) {
var i = j.which;
var h = b(this).val();
if (i>0 && (i<48 || i>57)) {
if (d == true && i == 46) {
if (g == true && a(this) == 0 && h.charAt(0) == "-") {
return false
}
if (h.match(/[.]/)) {
return false
}
}
else {
if (g == true && i == 45) {
if (h.charAt(0) == "-") {
return false
}
if (a(this) != 0) {
return false
}
}
else {
if (i == 8) {
return true
}
else {
return false
}
}
}
}
else {
if (i>0 && (i >= 48 && i <= 57)) {
if (g == true && h.charAt(0) == "-" && a(this) == 0) {
return false
}
}
}
});
return this
};
function a(d) {
if (d.selectionStart) {
return d.selectionStart
}
else {
if (document.selection) {
d.focus();
var f = document.selection.createRange();
if (f == null) {
return 0
}
var e = d.createTextRange(), g = e.duplicate();
e.moveToBookmark(f.getBookmark());
g.setEndPoint("EndToStart", e);
return g.text.length
}
}
return 0
}
}(jQuery));
$(function() {
$("#anyNumber").numericInput({ allowFloat: true, allowNegative: true });
});
</script>
最好的方法(允许所有类型的数字-实负,实正,iinteger负,整数正)是:
$(input).keypress(function (evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
var objRegex = /^-?\d*[\.]?\d*$/;
var val = $(evt.target).val();
if(!regex.test(key) || !objRegex.test(val+key) ||
!theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
};
});
如果你正在尝试有棱角的,这可能会有帮助
获取输入的数字(带小数点),然后
<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
现在这将不能正确地更新模型中的值 为了显式地改变model的值,添加这个
<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" (change)="data = $event.target.value">
更改事件将在模型中的值更新后触发,因此它也可以用于响应式表单。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求