jQuery-仅允许两个十进制值 [英] jQuery - Allow only two decimal values

查看:76
本文介绍了jQuery-仅允许两个十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

<input onkeypress="return isNumberKey(event)" type="number" value="" />

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46){   
        return false;
    }   
    return true;
}

以上功能允许用户输入两个以上小数点的值,即10.5678.如何修改函数并限制用户输入最多两位小数的值,即10.56

The above function allows user to enter value with more than two decimal i.e. 10.5678. How can I modify the function and restrict user to enter values upto two decimal i.e. 10.56

推荐答案

尝试以下代码 给元素指定类号

Try below code give class number to element

$('.number').on('keypress',function (event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
    var input = $(this).val();
    if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
        event.preventDefault();
    }
});

和javascript

and for javascript

function isNumberKey(evt){
  
console.log(evt.value);
  if ((evt.which != 46 || evt.value.indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
        //event it's fine

    }
    var input = evt.value;
    if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
        return false;
    }
}

<input onkeypress="return isNumberKey(this)" type="number" value="" />

这篇关于jQuery-仅允许两个十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆