Friday, April 20, 2012

Javascript, for-loop, not carrying the value

The form that fetches the value:



<input name="validatecard" type="text" id="myCardNumber"> 
<input onclick="isLuhn()" type="button" value="Check Credit Card" />


The Javavascript:



function isLuhn(cardnumber) {
var number_element = document.getElementById('myCardNumber');
var cardnumber = number_element.value;

e= '';
i= '';
var sum1 = 0;
var sum2 = 0;
for(i = cardnumber.length; i > 0; i -=2){
sum1 = sum1 * i;

for (e = cardnumber.length; e > 0; e -=2){
sum2 = sum2 + e;
}}}


I want this loop to for the value of cardnumber, say 4000 0000 0000 0302, start at the second to last number in the first loop and the last number and iterate backwards to 0.
I want every number that the loop iterates over to be added to sum1/sum2.
So if the above number assumed, iterating from the last
sum1 = 2 + 3 + 0 + 0 + 0 + 0 + 0 + 0. Right now it is working the the length of the cardumber which is 16 and goes 14, 12, 10, 8, 6 etc.. How do I set it right?





No comments:

Post a Comment