简体   繁体   English

使用Jquery自动将文本字段输入自动限制为数字?

[英]using Jquery to autolimit text field input to numbers only?

been doing some research, but haven't found a solution for me. 一直在做一些研究,但还没有为我找到解决方案。 Basically, I have a small admin section that requires number inputs for calculations. 基本上,我有一个小的管理部分,需要数字输入进行计算。 ONLY numbers. 只有数字。 BUT, the user can sometimes COPY AND PASTE including a $ or % character. 但是,用户有时可以复制和粘贴包括$或%字符。

Now, I have found this: input field, only numbers jquery/js 现在,我发现了这个: 输入字段,只有数字jquery / js

$("input[type=text]").keypress(function (e){
  var charCode = (e.which) ? e.which : e.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
});

which works perfectly during TYPING, however, if the user copies and pastes "$1230", it keeps the $ in there. 但是,如果用户复制并粘贴“$ 1230”,它会在$ TY30中完美地工作。 I would like it to auto-strip it.... 我希望它能自动剥离它....

SO, basically, I am thinking instead of "return false", I need some sort of "replace"? 所以,基本上,我在思考而不是“返回虚假”,我需要某种“替换”? Would that be the best way to go? 这是最好的方式吗?

Use on instead of keypress , with events for both keypress and change : 使用on而不是keypress ,同时包含keypresschange事件:

$("input[type=text]").on("keypress change", (function (e){
  var charCode = (e.which) ? e.which : e.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
});

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

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