我有3个div,我需要将它们仅接受数字。
我试图附加“ onkeypress”功能,但它仍然接受数字。
这里有人可以帮助我吗?我似乎找不到问题的根源。

这是代码:

document.getElementById("cc-num").maxLength = 16;
document.getElementById("zip").maxLength = 5;
document.getElementById("cvv").maxLength = 3;
$("#cc-num").append("onkeypress='return event.charCode >= 48 &&
event.charCode <= 57'");// makes the Card Number div only digit
available.
$("#zip").append("onkeypress='return event.charCode >= 48 &&
event.charCode <= 57'"); // makes the Zip div only digit available
$("#cvv").append("onkeypress='return event.charCode >= 48 &&
event.charCode <= 57'"); // makes the cvv div only digit available.

最佳答案

为了访问该事件,您需要keypress事件来调用一个函数,该函数会将事件作为参数传递给它。

此外,请勿使用内联HTML事件属性(即onkeypress)。这就是25年前建立的事件处理程序的方式,并且由于某些上帝被遗忘的原因,它不会消失。有些many reasons不使用它们,而是遵循基于标准的现代方法。



// Set up your event callbacks in JavaScript, not with inline HTML attributes.

// The function you supply as the callback will automatically
// recieve a reference to the event
$("#cc-num").on("keypress", function(evt){
 if(evt.charCode >= 48 && evt.charCode <= 57){
   console.log(evt.charCode);
 } else {
   evt.preventDefault();  // Cancel the event
 }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cc-num">





顺便说一句,如果使用HTML5 input type="number",则不需要任何此代码,因为首先只允许数字输入。



<input type="number">





或者,因为您有模式,所以文本框上带有信用卡正则表达式的HTML5 pattern属性可以解决问题:



:valid { background-color:rgba(0,255,0,.3); }
:invalid { background-color:rgb(255,0,0,.3); }

<input type="text" pattern="\d{4}-\d{4}-\d{4}">

10-06 15:42
查看更多