【问题标题】:number input numeric only [duplicate]数字仅输入数字[重复]
【发布时间】:2017-03-22 05:00:03
【问题描述】:

我有一个项目,我只想获取数字作为输入,所以我使用数字类型的输入,但这也允许使用十进制分隔符等。我将如何防止使用 , . 和 @987654323 @。

我环顾四周,找不到一个给出所需结果的结果,sinds 他们要么没有阻止十进制输入,要么仍然允许用户将其粘贴到字段中。

我有可以使用的 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').input(function(){this.value=this.value.replace(/\D/g,'')}
  • @Liam 我只想要数字 0-9,我认为它之前已经被问过,因为它不会是一个罕见的问题。但是我没有通过搜索找到它,或者它的答案并不能完全满足我的需求。

标签: javascript jquery html input


【解决方案1】:

试试这个代码

$(".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;
}
});

别忘了创建一个错误类。

【讨论】:

  • 因为这是在按键上,它永远不会过滤粘贴的内容。这是我发布的第二个功能的唯一问题
  • @maam27 与此一起使用 onBlur
  • 您可以使用on() 函数并将多个事件侦听器放在一个规则中check this answer
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 2017-07-09
  • 2017-08-03
相关资源
最近更新 更多