Skip to content
Advertisement

Javascript to identify card number

I’m using a piece of JavaScript code to identify what type of credit card number a user enters. I don’t know much about JavaScript and am using code found on the web. I’ve gotten it to work with no issue, but I was hoping someone could explain to me why a specific part works the way it does.

When a user starts to enter the credit card number, the value that gets used by the JavaScript function isn’t the same as the number. For example, when I enter a 3, the charCode variable is 51. I’m just trying to understand how I get from 3 to 51 so I can use this function for additional card types.

JAVASCRIPT:

<script type="text/javascript">
function handleKeypress(inCardNumber,e) {
    var inCardNumber = document.form.cardNumber;

    var charCode;
    if(e && e.which) {
        charCode = e.which; // For Firefox
    }
    else if(window.event){
        e = window.event;
        charCode = e.keyCode; // For IE
    }

    if (inCardNumber.value.length === 1) { 
        switch (charCode) {
        case (48):
            swapVISA.src = "/images/icons/payments/VISA-dim.png";   
            break;
        case (49):
            swapVISA.src = "/images/icons/payments/VISA-dim.png";
            break;


etc

HTML

onkeyup="handleKeypress(this,event);"

Advertisement

Answer

Character codes are just a representation of a key, they are just a standard of which code corresponds to what keystroke, so don’t think too much about them. Just remember that every key on your keyboard has a character code associated with it.

Here’s a list of char codes as well as an interactive tool to test them out: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

As UweB pointed out, get the actual character from a code like this:

var theChar = String.fromCharCode(charCode);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement