Chris McKechnie Chris McKechnie - 1 month ago 9
Javascript Question

Adding up particular part of String from a Value input

I'm now working on a piece of code where I need to add the first 3 characters on the string, and then compare them to the last 2 characters to make sure they match.


e.g: ID 12306 is Valid, as 1+2+3 = 6, and 0+6 = 6.


I did find a topic previously on here (back in 2012) regarding a similar issue, however the code example used 2 static number variables, and when I tried to implement the same method using my HTML input value, it seems to do nothing.

var custId = document.getElementById("custid").value;

function validateId(custid) {
var custId2 = custId;
var custId3 = custId;

custId2 = custId2.substring(0, 2);
custId3 = custId3.substring(3, 5);

custid = custid.split('');
var sum = 0;

for (var i = 0; i < custid.length; i++) {
sum += parseInt(custid[i], 10);
}

return sum;

if (add(custId2) != add(custId3)) {
output = "ID error. The first three digits must sum to the value ' +
'of digits 4 and 5. e.g. 12306 is a valid value";
output = custId2 + "<br />" + custId3;
addToOutput();
return false;
}
}



Answer

Though your method has numerous issues as stated in the comments (incorrect casing, multiple returns, substring index), I have provided a solution you can use to your liking.

var validateId = function(custId) {
  var custId2 = custId.substring(0, 3).split('');
  var custId3 = custId.substring(3,5).split('');

  var sum2 = 0; 
  var sum3 = 0; 

  custId2.forEach((e) => {
    sum2 += parseInt(e);
  })

  custId3.forEach((e) => {
    sum3 += parseInt(e);
  })

  if(sum2 !== sum3) {
    console.log("ID error. The first three digits must sum to the value of digits 4 and 5. e.g. 12306 is a valid value")
  } else {
    console.log("Success");
  }
}

validateId("12306"); 

Example - http://plnkr.co/edit/vtrU8Hs4Bv6FJS1qFnKn?p=preview

Comments