简体   繁体   English

在iOS上动态限制数字输入中的特殊字符

[英]Dynamically restrict special characters in number input on iOS

I've seen a bunch of questions that are similar to this but not quite what I am looking for... apologies if I've missed one. 我见过很多与此类似的问题,但不是我要找的问题。如果我错过了,很抱歉。

So, I have a series of number inputs for an HTML app that runs in an iOS UIWebView and mobile Safari. 因此,我为在iOS UIWebView和移动Safari中运行的HTML应用程序提供了一系列数字输入。 They need to accept only numbers and not special characters or letters and must validate to a max value. 他们只需要接受数字,而不接受特殊字符或字母,并且必须验证为最大值。

I'm currently using e.which to validate, which is working most of the time, but of course a bunch of punctuation characters (despite being different keys on iOS) report the same keycode as number keys, and I'm having trouble figuring out if I can just not allow them to be entered vs stripping them out after they've displayed in the input field. 我目前正在使用e.which进行验证,大多数情况下都可以使用它,但是当然,一堆标点符号字符(尽管iOS上的不同)报告的键码与数字键相同,并且我在确定时遇到问题如果我不能允许他们输入,或者将它们显示在输入字段中,然后将它们剥离。

(Irrelevant code and structure has been removed.) (不正确的代码和结构已删除。)

<input type="number" id="input-patients" value="1600" max="10000" min="0" />
<input type="number" id="input-pct_dropout" value="16" max="100" min="0" />
<input type="number" id="input-annual_dollars" value="275" max="500" min="0" />

JavaScript: JavaScript的:

$('.input').on('keydown', function(e){

    var charCode = (e.which) ? e.which : event.keyCode;
    if (charCode > 47 && charCode < 59 || charCode == 8){
    // here a bunch of other stuff happens
       return true;
    }
    else{
       return false;
    }
});

Can I check for special characters without having them display in the input fields first and then stripping them from the string? 我是否可以先检查特殊字符而不先将它们显示在输入字段中,然后再将它们从字符串中删除?

Thanks in advance. 提前致谢。

onkeyup of selected input element write event: get value from input box, then check is number? 所选输入元素的onkeyup写事件:从输入框中获取值,然后检查是否为数字? (if yes then isNAN(val) return false and stop further processing), else go for next execution which call recursive function turnToInt and set value of this input box with valid INT returned from that function; (如果是,则isNAN(val)返回false并停止进一步处理),否则继续执行下一个调用递归函数turnToInt的步骤,并使用该函数返回的有效INT设置此输入框的值;

turnToInt function : check is valid number (if yes return that number or remove last character from val and call itself for further validation finally return valid INT number); turnToInt函数:检查有效数字(如果是,则返回该数字或从val中删除最后一个字符,并对其进行调用以进行进一步验证,最后返回有效的INT数字);

$(".select_object").keyup(function() {
      (val = $(this).val()) && isNaN(val) && $(this).val(turnToInt(val))
    });

function turnToInt(val) {
    return isNaN(val) ? turnToInt(val.substr(0,val.length-1)) : val;
  }

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

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