Search code examples
javascriptsumchecksumparseinttofixed

parseInt value from input and use as a check for the sum of last value with Javascript


Trying to track the numbers in an input value and use these as a checkdigit for the last number. Basically, grab the first nine digits of the input, run some simple math and then add those numbers together. Take that total, divide by two then use the remainder as the check digit.

Thus far unsuccessful so if anyone has a good idea of where I am going wrong would gladly appreciate it. I put a fiddle up here: Das Fiddle

 window.onkeyup = keyup;
 var inputTextValue;

 function keyup(e) {
  inputTextValue = e.target.value;
  $('#numberValue').text(inputTextValue);
        // must be 10 characters long
        if (inputTextValue.length !== 10) {
            return false;
        }

        // run the checksum
        var valid = false;
        try {
            var sum = (parseInt(inputTextValue[0], 10) * 2) +
                (parseInt(inputTextValue[1], 10) * 3) +
                (parseInt(inputTextValue[2], 10) * 4) +
                (parseInt(inputTextValue[3], 10) * 2) +
                (parseInt(inputTextValue[4], 10) * 3) +
                (parseInt(inputTextValue[5], 10) * 4) +
                (parseInt(inputTextValue[6], 10) * 2) +
                (parseInt(inputTextValue[7], 10) * 3) +
                (parseInt(inputTextValue[8], 10) * 4);

            var checkNumber = 0;

            if ((sum % 10) > 0) {
                checkNumber = (sum % 10).toFixed(-1);
            }

            if (inputTextValue[9] === ("" + checkNumber)) {
                valid = true;
                alert(checkNumber)

            }
        } catch (e) {
            valid = false;
        }

        return valid;

}


Solution

  • You should be using :

       checkNumber = (sum % 10).toFixed(0);
    

    toFixed(-1) will return 0.

    Fiddle here