javascript输入只允许数字
问题描述:
我使用此代码并且可以使用
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>
但我无法访问html,只有javascript
but I do not have access to the html, and have only javascript
document.getElementById("txtChar").addEventListener("keypress", <<your code>>, false);
应该采用什么<< your code>>
?
p.s。发现这个组件的另一个错误:
当你复制粘贴(ctrl-v或右击 - 粘贴)它不起作用
有人知道如何解决它
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
答
如果您使用 HTML5
很酷,并且只针对现代浏览器,新属性必需
和模式
随时为您服务。示例:
If you're cool in using HTML5
and only target modern browsers, the new attributes required
and pattern
are here for you. Example:
<input id="txtChar" type="number" required pattern="\d+"/>
您可以通过 CSS 来解决状态
#txtChar:required:valid {
border: 1px solid green;
}
#txtChar:required:invalid {
border: 1px solid red;
}
如果在< form>中使用
标记,用户将无法以无效状态提交。
If used within a <form>
tag, a user won't be able to submit in invalid state.
我刚看到你无法访问标记,所以道歉。我将把它留作信息性答案。