Capture credit card information from card reader into an uneditable text field

trishulpani picture trishulpani · May 10, 2012 · Viewed 8k times · Source

I'm newbie in terms of Javascript. Here's my problem:

I wish to capture credit card information from a card reader and then process it. So far, I've been able to capture dummy credit card data in an HTML textbox field - its no rocket science actually, 'cos the card reader input is just a set of keyboard events when a card is swiped through a card reader. The issue is that it works only when there is a cursor focus on a text field. If i turn the textfield into a read only box, it doesn't work - which is my exact requirement. I should be able to mask the input, show a couple of *s and I should be able to make the field non-editable. I'm hoping this could be done using a transparent div placed on the textbox - but I have no idea how that can be achieved.

I'm open to other ideas too.

Answer

ZachB picture ZachB · May 11, 2012

You can use javascript to set a disabled text field's value, and to get keystroke event data through document.onkeydown = function(e) { ... }. No need for hidden divs.

I assume you have other fields on your page, which will make it difficult to know when to capture the card reader data. Are you fortunate enough that your credit card reader sends some unique first character(s) so you know the keyboard events are coming from the reader and not user keystrokes? If so, then you can listen for those particular key strokes so you don't have to worry about setting focus. Otherwise maybe consider a button like "Read Credit Card" that has an on("click") function set to read the next xx digits.

Here's some debugging code you can use to see if your reader sends any unique characters that you can listen for:

document.onkeydown = function(d) {
    console.log( d.which ? d.which : window.event.keyCode);
};

It's conceivable that there's some other unique event information when the reader is used. Maybe check the device's manual.