javascript javascript输入只允许数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14585407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript input allowing only numbers
提问by MaksiK
i use this code and it works
我使用此代码并且它有效
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
</BODY>
</HTML>
but I do not have access to the html, and have only javascript
但我无权访问 html,只有 javascript
document.getElementById("txtChar").addEventListener("keypress", <<your code>>, false);
what should be in place <<your code>>
?
什么应该到位<<your code>>
?
p.s. found another bug with this component:
when you copy-paste(ctrl-v or right click-paste) it does not work
can someone know how to resolve it
ps 发现此组件的另一个错误:
当您复制粘贴(ctrl-v 或右键单击粘贴)时,它不起作用
有人知道如何解决它
回答by jAndy
If you're cool in using HTML5
and only target modern browsers, the new attributes required
and pattern
are here for you. Example:
如果您擅长使用HTML5
并且只针对现代浏览器,那么新属性required
和pattern
就在这里为您服务。例子:
<input id="txtChar" type="number" required pattern="\d+"/>
and you can address the state via CSSlike
你可以通过CSS来处理状态,比如
#txtChar:required:valid {
border: 1px solid green;
}
#txtChar:required:invalid {
border: 1px solid red;
}
If used within a <form>
tag, a user won't be able to submit in invalidstate.
如果在<form>
标签内使用,用户将无法以无效状态提交。
I just read that you don't have access to the markup, so apologizes. I'll just leave it as informational answer.
我刚刚读到您无权访问标记,因此深表歉意。我只会把它作为信息性答案。
回答by Josaph
In <<your code>>
add the name of the function to handle it, isNumberKey
in this case; and also you need to add evt.preventDefault();
before return false;
在这种情况下,<<your code>>
添加处理它的函数的名称isNumberKey
;并且您还需要在evt.preventDefault();
之前添加return false;
This function below only accepts codes corresponding to digits from 0 to 9 and ignores dots ("."), hyphens ("-") and minus signs ("?").
下面的这个函数只接受对应于 0 到 9 数字的代码,并忽略点(“.”)、连字符(“-”)和减号(“?”)。
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46 || charCode > 31 && (charCode < 48 || charCode > 57)){
evt.preventDefault();
return false;
}
return true;
}
Configure the input field for HTML5 browsers:
为 HTML5 浏览器配置输入字段:
txtChar = document.getElementById("txtChar")
txtChar.addEventListener("keypress", isNumberKey, false);
//Attributes
txtChar.type = "number";
txtChar.min = 0;
txtChar.pattern = "\d+";
txtChar.placeholder = "Only integer positive numbers";
txtChar.required = "required";
Working example including styling from jAndy's answer: http://jsfiddle.net/pL9Zk/
工作示例,包括 jAndy 的回答中的样式:http: //jsfiddle.net/pL9Zk/
回答by wrecklez
Try this code bro. i hope it will help you a lot i use jQUERY.
试试这个代码兄弟。我希望它会帮助你很多我使用 jQUERY。
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="txtChar" type="text" name="txtChar">
</body>
<script>
$("#txtChar").keypress(function(e) {
var charCode = (e.which) ? e.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
});
</script>
回答by Nobita
If you can't go with HTML5 <input type="number">
then I would regex the input value allowing only numbers. I modified a script I wrote to accomplish a similar task. It allows pasting and strips any non-integer character.
如果您不能使用 HTML5,<input type="number">
那么我将正则表达式只允许数字的输入值。我修改了我编写的脚本来完成类似的任务。它允许粘贴和剥离任何非整数字符。
var arrowKeys = [37, 38, 39, 40];
function stripChars( e ) {
// Don't execute anything if the user is just moving the cursor around and
// not really entering anything new.
if(arrowKeys.indexOf(e.keyCode) !== -1){ return; }
var elem = e.currentTarget,
cursorPos = elem.selectionEnd;
// strip any unwanted character and assign the value back
elem.value = elem.value.replace(/\D/g,'');
// this avoids the cursor shifting to the end of the input
// when inserting an integer in the middle of an already existing number
elem.selectionEnd = cursorPos;
elem.focus();
}
var elem = document.getElementById('elem');
elem.addEventListener('keyup', stripChars, false);
elem.addEventListener('paste', stripChars, false);
Anyway, you can view the original script with tests hereand a demo of the above code here.
回答by titanofold
I know I'm a little late to the party.
我知道我参加聚会有点晚了。
The HTML5 example by jAndy is probably the best answer for browsers that support it. The JavaScript answer by Josaph was good as well in that it inspired my answer to solve the questioner's addendum and my problem.
jAndy 的 HTML5 示例可能是支持它的浏览器的最佳答案。Joseph 的 JavaScript 答案也很好,因为它启发了我的答案来解决提问者的附录和我的问题。
The following throws away input that matches the regex (not a digit, replace with an empty string), and is invoked anytime there's input, even from a paste.
以下内容丢弃与正则表达式匹配的输入(不是数字,替换为空字符串),并在有输入的任何时候调用,即使是从粘贴中调用。
function stripNonNumeric() {
this.value = this.value.replace(/\D+/g, '');
}
var txtChar = document.getElementById("txtChar");
if (txtChar.addEventListener) {
txtChar.addEventListener("input", stripNonNumeric);
} else if (txtChar.attachEvent) {
txtChar.attachEvent("oninput", stripNonNumeric);
}
I'm not a JavaScript guy, I'm not sure if this is a good way to solve the problem, or if there are performance issues to consider. However, it works for me.
我不是 JavaScript 专家,我不确定这是否是解决问题的好方法,或者是否需要考虑性能问题。但是,它对我有用。
回答by Abhijeet Pawar
event is unknown inside function. So mention the event object to function:
事件在函数内部未知。所以提到要起作用的事件对象:
document.getElementById("myElement").addEventListener("keypress", function(event){
return isNumberKey(event);
}, false);
document.getElementById("myElement").addEventListener("keypress", function( event){ return isNumberKey(event); }, false);
EDIT:
The question changed a bit, so quoting the answer:
1. Change "myElement" to "txtChar"
2. include event object as parameter
编辑:问题有所改变,因此引用答案:
1. 将“myElement”更改为“txtChar”
2. 包含事件对象作为参数
document.getElementById("txtChar").addEventListener("keypress", function(event){
return isNumberKey(event);
}, false);
回答by Waji
It's a mistake?
这是一个错误?
document.getElementById(**"txtChar"**).addEventListener("keypress", function(){
return isNumberKey(event);
}, false);