有一个快速的方法来设置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>
其他回答
我用完了这个函数:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"
这在IE和Chrome中工作得很好,我不知道为什么它在firefox中也不工作得很好,这个功能在firefox中阻止了tab键。
对于tab键在firefox中工作很好,添加这个:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"
这是一个改进的函数:
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
jQuery的另一个简单方法:
$('.Numeric').bind('keydown',function(e){
if (e.which < 48 || e.which > 57)
return false;
return true;
})
现在只需将每个输入类设置为Numeric,如下所示:
<input type="text" id="inp2" name="inp2" class='Numeric' />
//在JavaScript函数中(可以使用HTML或PHP)。
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
在您的表单输入:
<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>
输入max。(以上这些允许使用12位数字)
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求