简体   繁体   English

仅允许数字输入,包括负数和十进制

[英]Allow only numeric input, including negative and decimal

This question deals with allowing only numeric characters to be entered in an input text field. 该问题涉及只允许在输入文本字段中输入数字字符。 I am needing to do the same thing, except that negative sign and decimal must be allowed. 我必须做同样的事情,除了必须允许负号和十进制。 Also the solution needs to work in Mobile Safari, for iOS 6 and iOS 7 . 该解决方案还需要在iOS 6iOS 7的 Mobile Safari中工作。

I have tested the accepted solution which is based on checking keycodes in the keyup event handler, but this solution does not work on my iPad because it allows the following characters to be entered: 我已经测试了接受的解决方案,该解决方案基于检查keyup事件处理程序中的密钥 代码 ,但是该解决方案在我的iPad上不起作用,因为它允许输入以下字符:

()$&@!

The code below is based on this solution : 以下代码基于此解决方案

('input.numeric').keyup(function(e) {
    this.value = (this.value.replace(/[^0-9.\,-]/g, ''));
});

Although this code works well in desktop browsers that I have tested (eg Chrome), on Mobile Safari it does not seem to work very well. 尽管此代码在我测试过的台式机浏览器(例如Chrome)中运行良好,但在Mobile Safari上似乎效果不佳。 On iOS 5 , this does allow numeric characters and the minus sign to be entered, but it results in the cursor position acting strangely with the cursor often appearing before the entered character. iOS 5上 ,这的确允许输入数字字符和减号,但是这导致光标位置的行为异常,光标通常出现在输入的字符之前。 On iOS 6 , for some reason this does not allow the minus sign to be entered, only numeric characters. iOS 6上 ,由于某些原因,这不允许输入减号,只能输入数字字符。

Does anyone have a solution that does work correctly on Mobile Safari . 是否有人有在Mobile Safari上正常工作的解决方案。 I am looking for a pure Javascript solution here, or one that depends only on jQuery . 我在这里寻找一种纯Javascript解决方案,或者仅依赖jQuery的解决方案。 Please don't answer with "use this or that library" or make comments about Javascript validation not being safe. 请不要回答“使用这个或那个库”,也不要发表有关Javascript验证不安全的评论。

Have a look at this... 看看这个...

var prevVal = '';
$(".numericValue").on("input", function (evt) {
    var self = $(this);
    if (self.val().match(/^-?\d*(\.(?=\d*)\d*)?$/) !== null) {
        prevVal = self.val()
    } else {
        self.val(prevVal);
    }
    if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57) && (evt.which != 45 && self.val().indexOf("-") == 0)) {
        evt.preventDefault();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM