0

I have 3 divs that i need to put them only accepting numbers. I have tried to append the "onkeypress" function but it still accepts numbers. Is there anyone here that can help me out? I cant seem to find where the problem relies.

This is the code:

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.
  • Not sure you want to use `$(...).append(...)` to append an event listener. Since you are using jQuery, consider using the `.on()` syntax. – Forty3 Dec 14 '17 at 20:34
  • `$("#zip").append("onkeypress='return event.charCode >= 48 && ` not even close – epascarello Dec 14 '17 at 20:35
  • Suggested reading for you. jQuery `.on` http://api.jquery.com/on/ which attaches event listeners. And the possible events https://api.jquery.com/category/events/ – Andrew Lohr Dec 14 '17 at 20:41

1 Answers1

2

In order to have access to the event, you need your keypress event to invoke a function that will have the event passed to it as an argument.

Additionally, don't use inline HTML event attributes (i.e. onkeypress). That's how event handlers were set up 25 years ago and for some God forsaken reason, will not go away. There are many reasons not to use them and instead follow modern, standards-based approaches.

// 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">

By the way, if you use the HTML5 input type="number", you won't need any of this code, as only numeric input is allowed in the first place.

<input type="number">

Or, because you have a pattern, the HTML5 pattern attribute on a textbox with a regular expression for a credit card would do the trick:

: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}">
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71