var cards = new Array();
cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true};
cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4844,4508,4026,4917,4913", checkdigit: true};
cards [2] = {name: "MC", length: "16", prefixes: "51,52,53,开发者_如何学Python54,55", checkdigit: true};
then my functions:
function CardTypes()
{
for (var i=0; i<cards.length; i++) {
if cards.name.Validate(PaymentForm.CardNumber.value)<!--pretty sure this is wrong-->
cardname = cards[i].getCardType();
}
if (cardname.length > 0) {
alert("This looks like a " + cardname + " .");
};
};
When the form is submitted it calls the Validate function which in turn calls all the other functions including CardTypes(). Id like to be able to determine the card type by the card prefixes i.e. 4 = visa. I'm pretty sure i have completely messed up the CardTypes() function. Any help would be appreciated. My form id is PaymentForm.
function CardTypes()
{
var givenValue = PaymentForm.CardNumber.value;
for (var i = 0; i < cards.length; i++) {
var cardPrefixes = cards[i].prefixes.split(',');
var leave = false;
for (var j = 0; j < cardPrefixes.length; j++) {
if (givenValue.indexOf(cardPrefixes[j]) === 0) {
return cards[i].name;
}
}
}
}
This should work.
What is PaymentForm.CardNumber.value
set to? Is it the whole number of the card?
var cardNumber = PaymentForm.CardNumber.value;
If that's right you would then want to read all the prefixes e.g.
for (var i=0; i<cards.length; i++) {
var prefixes= cards[i].prefixes;
var prefixArray = prefixes.split(",");
for(var j=0; j < prefixArray.length; j++) {
if(cardNumber.startsWith(prefixArray[j])) {
alert("Card Type is " + cards[i].name);
}
}
}
// Add this method to String
String.prototype.startsWith = function(str){
return (this.indexOf(str) === 0);
}
JSFiddle: http://jsfiddle.net/KDTPX/
精彩评论