有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
希望我不是用一个丑陋的棍子在这里打死马,但我用这个为我的网站数量输入,它只允许从1到99的数字。
试一试: https://jsfiddle.net/83va5sb9/
<input min="1" type="text" id="quantity" name="quantity" value="1"
onKeyUp="numbersonly()">
<script>
function numbersonly() {
var str = document.getElementById("quantity").value
var newstr = ""
for (i = 0; i < str.length; i++) {
for (ii = 1; ii < 10; ii++) {
if (str.charAt(i).indexOf(ii) > -1) {
newstr += str.charAt(i)
}
}
}
if (newstr == "") {
newstr = 1
}
if (parseInt(newstr) > 99) {
newstr = 99
}
document.getElementById("quantity").value = newstr
}
</script>
其他回答
正则表达式和匹配函数可以很好地处理这种情况。例如,我使用下面的代码来验证图上作为坐标的4个输入框。它运行得相当好。
function validateInput() {
if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
location.reload();
}
}
对于喜欢说俏皮话的人。
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";
:)
你也可以比较输入值(默认情况下被视为字符串)和它本身被强制为数字,比如:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
然而,你需要绑定到事件,如keyup等。
HTML5有<input type=number>,这听起来很适合你。目前,只有Opera原生支持它,但有一个项目有一个JavaScript实现。
这是一个简单的解决方案
取代。price-input输入。数量与输入字段的类
$(".price-input input.quantity").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求