Skip to content

Instantly share code, notes, and snippets.

@YoSmudge
Created September 12, 2011 14:12
Show Gist options
  • Save YoSmudge/1211341 to your computer and use it in GitHub Desktop.
Save YoSmudge/1211341 to your computer and use it in GitHub Desktop.
Card Auto-selector (jQuery)
function detect_card(){
var types = {
Amex: [34,37],
Visa: [4],
Mastercard: [51, 52, 53, 54, 55],
Discover: [6011]
};
//Loop the options and build a regexp
$.each(types, function(i,opts){
$.each(opts, function(i2,rexp){
var re = new RegExp('^'+rexp);
if ( $('#card_number').val().match(re) ) {
//We have a match! Now find the correct card type
$('#card_type > option').each(function(i3,elm){
if ( $(elm).val() == i ) {
$(elm).attr('selected', true);
}
});
}
});
});
}
<input name="card_number" id="card_number" type="text" maxlength="255" style="width:208px;" onkeyup="detect_card();" />
<select name="card_type" id="card_type" style="width:120px;">
<option value="0">----</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="Discover">Discover</option>
<option value="Amex">Amex</option>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment