javascript - number 只能输入数字

标签 javascript jquery html input

<分区>

我有一个项目,我只想获取数字作为输入,所以我使用的是数字类型的输入,但这也允许使用小数点分隔符等。我如何防止使用 , .e.

我环顾四周,找不到能提供所需结果的,因为他们要么没有阻止小数输入,要么允许用户仍然将其粘贴到字段中。

我有可以使用的 javascript 和 jquery,但我不想使用外部库。

如果有人能够帮助我,我将不胜感激。

function LimitKeys($id) {        
    $field = document.getElementById($id);
    $value = $($field).val(); //if the value contains multiple e , or . the value is no longer valid and gives me blank
    console.log($value);
    $regex = /[^\d]/;

    $val = $value.replace($regex, "");// cant replace in blank
    console.log($val);
    //$($field).val($val);
}

$('.number-only').keypress(function (event) { //sinds it's on keypress it won't catch the paste of data.
    console.log(this.value);
    var regex = new RegExp("^[0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

最佳答案

试试这段代码

$(".number-only").on('input', function (e) {
 //if the letter is not digit then display error and don't type anything
 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //display error message
    $(".error").html("Only numbers allowed").show().fadeOut("slow");
           return false;
}
});

不要忘记创建错误类。

关于javascript - number 只能输入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40489097/

相关文章:

javascript - 在按钮处于事件状态时更改按钮的 css

javascript - 使用 for 循环时如何防止 json 数据被反转?

javascript - setTimeout 和事件传播

javascript - 如何让父DIV的子DIV充当父DIV

html - 如何防止表格中的这个 div 增加单元格高度?

Android 4.1 库存浏览器 : Can't open links in new tab

javascript - 如何在 Javascript 中设置可选参数的默认值?

javascript - 平滑滚动以锚定在同一页面上

html - 仅具有水平滚动的 Div 不起作用

javascript - 使用 console.log() 调试 ExtJS 4