External files not linking in VS Code - javascript

I'm very new to coding and thus VS Code. I am on a mac. Whenever I try to link an external file in VS Code to another file it never works. I understand it has to be a bad file path but I cannot figure it out at all. I've tried removing files from folders so they're in their own section and this does not work.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script src="/js/number-guessing-game.js"></script>
</body>
</html>
js file:
function runGame() {
let guessString = '';
let guessNumber = 0;
let correct = false;
let numtries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
// const target = Math.floor(Math.random() * 100) + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target);
} while (!correct);
alert('You got it! The number was' + target + '.\n\nIt took you' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target){
let correct = false;
if (isNaN(guessNumber)) {
alert('You have not entered a number.\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!');
} else if (guessNumber < target) {
alert('Your number is too small!');
} else {
correct = true;
}
} return correct;
}
Here's what file setup looks like:

You should pass the relative path instead of absolute:
<script src="js/number-guessing-game.js"></script>
Also you have syntax error in js, here is an working example:
function runGame() {
let guessString = '';
let guessNumber = 0;
let correct = false;
let numtries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
// const target = Math.floor(Math.random() * 100) + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target);
} while (!correct);
alert('You got it! The number was' + target + '.\n\nIt took you' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target) {
let correct = false;
if (isNaN(guessNumber)) {
alert('You have not entered a number.\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!');
} else if (guessNumber < target) {
alert('Your number is too small!');
} else {
correct = true;
}
return correct;
}

Related

While loop in js faulty

I'm creating a guess the number with limited guesses. I have add an incrementor to check the number of times a user submits an answer. Everything seems to work except the loop starts at the final iteration and the games ends on the first try.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<div>Guess The Number</div>
<input type="text" id="input">
<button id="btn">Check Answer</button>
<p id="guesses" style="display: inline-block;"></p>
<p id="hint"></p>
</body>
</html>
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
btn.addEventListener('click', () => {
if(isNaN(input.value)){
input.value = "Please type a number"
} else{
const hint = document.getElementById("hint");
let i = 0;
while (i < 10){
if(input.value === rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
break;
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else{
hint.innerHTML = "Too low";
} i++; guesses.innerHTML = "You have guessed " + i + " times";
}
if(i === 10){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
}
})
I've tried changing the number in the while loop condition. I've tried moving the incrementor in and out of the loops function. I've also tried chatgpt to see if it would work. But no luck. I would really appreciate your help.
I think you're misunderstanding the while loop. The loop will run once for every instance of i from 1 to 10 then stop running when the condition in the while loop is false. Based on what you mentioned you don't want a loop at all but to store the number of guesses into its own variable and increase that variable until you reach your limit.
const rndmNum = Math.floor(Math.random() * 100) + 1;
let numberOfGuesses = 0;
btn.addEventListener('click', () => {
if (isNaN(input.value)) {
return input.value = "Please type a number";
}
const hint = document.getElementById("hint");
if (input.value === rndmNum) {
hint.innerHTML = "Congratulations, You guessed correctly!";
return;
} else if (input.value > rndmNum) {
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
numberOfGuesses++;
guesses.innerHTML = "You have guessed " + numberOfGuesses + " times";
if (numberOfGuesses === 10) {
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
})
I believe this is what you were trying to accomplish. The reason why it's not working with the loop because it will run ten times with the click of the button once.
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
//keep track of guess count
let count = 0;
//event listner to check the users answer
btn.addEventListener("click", checkAnswer)
//this function will check for answers or display game over
function checkAnswer(){
if(count > 9){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
} else if(input.value == rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
count++
guesses.innerHTML = "You have guessed " + count + " times";
}

function doesn't register variable change

I'm trying to make a small game with Javascript where the user has to enter the sum of two random numbers (a and b).When you click on a button or when you press enter, it calls a function which checks if the sum is the same as what you entered. If that's the case, the function play() is called again and a and b change. It works fine the first time, but the second time, unless the second sum is equal to the first one, it doesn't work. What does my answer() function acts as if a and b didn't change ?
let count = 0;
function play() {
if (count < 10) {
// setTimeout(loss, 30000);
count += 1;
document.getElementById("user-answer").value = "";
var a = Math.floor(Math.random() * 20) + 1;
var b = Math.floor(Math.random() * 20) + 1;
var question = document.getElementById("question");
question.textContent = a + " + " + b;
function answer() {
var result = a + b;
var userAnswer = document.getElementById("user-answer").value;
if (userAnswer == result) {
sound.play();
//clearTimeout();
play();
}
if (userAnswer != result) {
document.getElementById("user-answer").classList.add("wrong");
// document.getElementById("user-answer").disabled = true;
console.log(result);
console.log(userAnswer);
// setTimeout(remove, 1000);
}
}
window.addEventListener("keypress", function(event) {
if (event.key == "Enter") {
answer();
}
})
document.getElementById("send-answer").addEventListener("click", answer);
} else {
document.getElementById("win").textContent = "You won!";
}
}
Well, calling play repeatedly will create new local variables a and b and new instances of answer function closing over those a, b and will add new event listeners every time. You could:
move the declaration of answer outside play
share a,b across answer and play
add event listeners only once
Here is somewhat refactored version for a start:
(function () {
let count = 0;
let a = 0, b= 0;
function play() {
if (count < 10){
// setTimeout(loss, 30000);
count += 1;
document.getElementById("user-answer").value = "";
a = Math.floor(Math.random() * 20) + 1;
b = Math.floor(Math.random() * 20) + 1;
var question = document.getElementById("question");
question.textContent = a + " + " + b;
} else {
document.getElementById("win").textContent = "You won!";
}
}
function answer(){
var result = a + b;
var userAnswer = document.getElementById("user-answer").value;
if(userAnswer == result){
//sound.play();
//clearTimeout();
play();
}
if(userAnswer != result) {
document.getElementById("user-answer").classList.add("wrong");
// document.getElementById("user-answer").disabled = true;
console.log(result);
console.log(userAnswer);
// setTimeout(remove, 1000);
}
}
window.addEventListener("keypress", function(event){
if (event.key == "Enter"){
answer();
}
})
document.getElementById("send-answer").addEventListener("click", answer);
play();
})()
<div>
<div id="question">
</div>
<input type="text" id="user-answer"/>
<input type="button" id="send-answer" value="Send answer"></input>
<div id="win">
</div>
</div>

What is wrong with this incremental logic for a game scoring system?

When I am incrementing and decrementing a score (specifically scoreVar variable) in my game in JavaScript and HTML it does not work as it should, it does not increment always when a right answer is given (often staying at zero or last inputted number) or neither decrement when a wrong answer is given in the same way, is there anything I am doing wrong here?
I have updated the below codes to add a new checking aspect, that if the score goes below 0 it should then stay at zero. This kind of works, but each time it will get stuck at -1 instead when doing this and cannot figure out why? I think it was a good attempted fix though that shows more what I am aiming to do and that this question is not related to type but more a single variable (scoreVar) which I am having issues with incrementing and decrementing.
At the moment I can't see enough evidence working, documentated and theoretical that the type of the text box impacts a variable that is not specifically assigned or manipulated by the text box, unless I missed something there?
Please note the initial code, does not run, but the code below is more detailed and it does. I just put that initial code there for simplicity sake / to make the reading of my problem easier.
if (answerInput.value == summation)
{
scoreVar++;
if (scoreVar >= 0) {
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar <= 0)
{
scoreVar = 0;
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar < 0)
{
timeleft = 0;
}
}
else if (answerInput.value != summation) {
scoreVar--;
if (scoreVar >= 0){
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar <= 0)
{
scoreVar = 0;
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar < 0)
{
timeleft = 0;
}
}
So from here I have tried to look at the documentation specifically, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment I see you have postfix and prefix, but I don't believe as attempted prefix is the right fix here? Unless I am not coding it in the right way in its entirety.
My other theory involves in the code below, that the order and speed of what happens when a correct or incorrect answer is given, is overlapping? For example I answer four questions quickly in succession as erratically as possible, where the issue usually occurs, say 3 wrong and 1 correct, the score then does not update quickly enough / to the right increment or decrement.
The full project code is listed below for a better context of what is happening:
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;
const select = (selector) => document.querySelector(selector);
function mathFunc(x, y, c) {
if (c === "+") return x + y;
else if (c === "-") return x - y;
else if (c === "*") return x * y;
else if (c === "/") return x / y; //Is the "/" in this in respect of the " " one only actually doing anything mathematical?
return -1;
}
/**
* Our main game starts here.
*/
function main() {
let num1;
let num2;
let summation;
let summation2;
let operators = ["+", "-", "*", "/"]; //Is the "/" in this in respect of the " " one only actually doing anything mathematical?
let op;
let scoreVar = 0;
let questionElem = select(".questionText");
let resultElem = select(".result");
let answerInput = select(".answer");
let scoreElem = select(".score")
scoreElem.innerHTML = "Score: " + scoreVar;
answerInput.addEventListener("keyup", (event) => {
if (event.keyCode === 13) {
event.preventDefault();
select(".Btn").click();
}
});
select(".Btn").addEventListener("click", handleSubmit);
function handleSubmit() {
resultElem.innerHTML = "Button has been clicked and text = " + answerInput.value;
if (answerInput.value == summation) {
resultElem.innerHTML = "Answer is " + summation + " so you are correct!";
console.log("Answer inputted: " + answerInput.value);
answerInput.value = "";
new Audio("correct.mp3").play();
scoreVar++;
console.log("Score: " + scoreVar);
if (scoreVar >= 0) {
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar <= 0)
{
scoreVar = 0;
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar < 0)
{
timeleft = 0;
}
setTimeout(function(){ (resultElem.innerHTML = ""); }, 1000);
questionAsk();
}
else if (answerInput.value != summation) {
resultElem.innerHTML = "Answer is " + summation + " so you are NOT correct!";
console.log("Answer inputted: " + answerInput.value);
answerInput.value = "";
new Audio("incorrect.mp3").play();
scoreVar--;
console.log("Score: " + scoreVar);
if (scoreVar >= 0){
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar <= 0)
{
scoreVar = 0;
scoreElem.innerHTML = "Score: " + scoreVar;
}
if (scoreVar < 0)
{
timeleft = 0;
}
setTimeout(function(){ (resultElem.innerHTML = ""); }, 1000);
questionAsk();
}
}
function questionAsk() {
op = operators[random(0, 4)];
num1 = random(1, 10);
num2 = random(1, 10);
summation = Math.round(mathFunc(num1, num2, op));
summation2 = (mathFunc(num1, num2, op));
let question = "What is " + num1 + " " + op + " " + num2 + "?";
questionElem.innerText = question;
console.log(question);
console.log("Summation / Answer with rounding = " + summation)
console.log("Summation / Answer without rounding = " + summation2)
}
let interval;
function timer() {
let timeleft = 350;
if (interval) clearInterval(interval);
interval = setInterval(function () {
if (timeleft <= 0) {
document.getElementById("countdown").innerHTML = "GAME OVER!";
document.getElementsByClassName("questionText")[0].innerHTML = "";
document.getElementsByClassName("result")[0].innerHTML = "";
document.getElementsByClassName("answer")[0].style.visibility = "hidden"; //alt is visible rather than hidden to show it again!
document.getElementsByClassName("Btn")[0].style.visibility = "hidden";
clearInterval(interval);
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
}
timer();
questionAsk();
}
main();
body {
font-family: 'Rubik', Arial, "Helvetica Neue", Helvetica, sans-serif;
font-size: 36px;
font-weight: lighter;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calcla</title>
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Rubik">
</head>
<body>
<p class="questionText"></p>
<label>
<input type="number" class="answer"/>
</label>
<button class="Btn">Submit</button>
<div class="result"></div>
<br>
<div id="countdown"></div>
<div class="score"></div>
<script src="math.js"></script>
</body>
</html>
I think your problem is there:
answerInput.addEventListener("keyup", (event) =>
{
if (event.keyCode === 13)
{
event.preventDefault();
select(".Btn").click();
}
});
I think using the KeyUp makes the preventDefault ineffective
Otherwise I revisited all your code, you should refocus your functions on a single technical subject, your code would be more readable
voila:
const
mF = document.forms['my-form']
, TimeEnd = 'TimeOut'
, TimeEndEvt = new Event(TimeEnd)
, Question =
{ score : 0
, response : 0
, timOut : 0
}
, displayTime = seconds => mF.countDown.textContent = !!seconds ? `${seconds} seconds remaining` : 'GAME OVER!'
, timmer = ( timeleft , displayFn = displayTime ) =>
{
const
one_Sec = 1000
, tim =
{ target : 0
, intRef : 0
};
tim.target = Date.now() + (timeleft * one_Sec)
displayFn(timeleft)
tim.Ref = setInterval(()=>
{
let sec = Math.floor((tim.target - Date.now()) / one_Sec)
if (sec>0) displayFn(sec)
else
{
clearInterval( tim.Ref )
displayFn(0)
mF.dispatchEvent(TimeEndEvt) // send End Event on form
}
}, 500)
}
, newQuestion =_=>
{
const
operators = '+-*/'
, random = (min, max) => Math.floor(Math.random() * (max - min)) + min
;
let
op = operators[random(0, 4)]
, n1 = random(1, 10)
, n2 = random(1, 10)
;
mF.question.textContent = `${n1} ${op} ${n2}`
switch (op)
{
case '+': Question.response = n1 + n2; break;
case '-': Question.response = n1 - n2; break;
case '*': Question.response = Math.round(n1 * n2); break;
case '/': Question.response = Math.round(n1 / n2); break;
}
console.clear()
console.log( `answer is ${Question.response}`)
mF.answer.value = ''
mF.answer.focus()
}
, CheckAnswser =_=>
{
let resp = Question.response
, answ = mF.answer.valueAsNumber
, Good = ( resp == answ )
;
Question.score += Good ? +1 : -1
mF.score.textContent = `Score: ${Question.score}`
mF.result.textContent = `Answer is: ${resp}, so you are ${Good?'':'Not '}correct! `
clearTimeout( Question.timOut )
Question.timOut = setTimeout(()=>{ mF.result.innerHTML = ' '},3000)
}
, haveAnswer = e =>
{
e.preventDefault()
CheckAnswser()
newQuestion()
}
newQuestion() // start Questionning !
timmer(60) // set timer delay...
mF.onsubmit = haveAnswer
mF.answer.onkeydown = e =>
{
if ( e.key === 'Enter' // some keybords have different return keys codes
&& mF.reportValidity() )
haveAnswer(e)
}
mF.addEventListener(TimeEnd, () => // use custom event to detect timer End
{
mF.btSubmit.disabled = true
mF.answer.disabled = true
mF.answer.blur()
mF.answer.value = ''
mF.question.innerHTML = ' '
console.clear()
}, false)
* {
font-family : Arial, Helvetica, sans-serif;
font-size : 24px;
}
output {
display : block;
font-size : 2em;
margin : 0 .7em;
}
input {
display : inline-block;
width : 10em;
margin : .7em 1em;
text-align : center;
}
output[name="result"] {
font-size : 1em;
color : lightslategrey;
}
<form name="my-form">
<output name="question"> </output>
<input name="answer" type="number" value="">
<button name="btSubmit" type="submit">Submit </button>
<output name="result"> </output>
<output name="countDown">countDown </output>
<output name="score">score </output>
</form>
let scoreVar = 0;
const btn1function = () => {
scoreVar++;
document.getElementById("score").innerHTML = "Score: " + scoreVar;
console.log("Score: " + scoreVar);
if (scoreVar >= 0) {
document.getElementById("score").innerHTML = "Score: " + scoreVar;
console.log("Score: " + scoreVar);
}
if (scoreVar <= -1)
{
document.getElementById("score").innerHTML = "Game Over";
scoreVar = 0;
console.log("Score: " + scoreVar);
}
};
const btn2function = () => {
scoreVar--;
document.getElementById("score").innerHTML = "Score: " + scoreVar;
console.log("Score: " + scoreVar);
if (scoreVar >= 0) {
document.getElementById("score").innerHTML = "Score: " + scoreVar;
console.log("Score: " + scoreVar);
}
if (scoreVar <= -1)
{
document.getElementById("score").innerHTML = "Game Over";
scoreVar = 0;
console.log("Score: " + scoreVar);
}
};
body {
font-family: 'Rubik', Arial, "Helvetica Neue", Helvetica, sans-serif;
font-size: 36px;
font-weight: lighter;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Rubik">
<button onclick="btn1function()">Increase</button>
<button onclick="btn2function()">Decrease</button>
<p id="score"></p>
So I added my own temporary solution to this for now so the answer is easier to understand for beginners. I still selected the above as an answer though, as technically its a more bug free way to do it, which was initially causing me issues. This code is more just for basic understanding of the logic than the 'best' solution.

Switch statement to check if something is in an predefined aray

How do i use a switch satement to check if the number divided by a number in an array == to 0.
how ive done it befor this is by using if statements and if else stateents to check:
if (i % num[0] == 0) {output thingy}
if (i % num[1] == 0) {output thingy}
and have an array named num.
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FizzBuzz</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<button onclick="plus()">+</button>
<button onclick="minus()">-</button>
<button onclick="zero()">0</button>
<h1>Number:</h1>
<h2 id="number">0</h2>
<h1>Value:</h1>
<h2 id="val">0</h2>
<script>
var output = "";
var val = document.getElementById("val");
var number = document.getElementById("number");
var i = 0;
function zero() {
i = 0;
number.innerHTML = (i);
output = "0";
val.innerHTML = (output);
}
function plus() {
i++;
thingy()
}
function minus() {
i--;
thingy()
}
function thingy() {
var num = [3, 5]; // The numbers to multiply
var out = ["Fizz", "Buzz"] // The outputs
number.innerHTML = (i);
output = "";
for (var i = 0; i < num.length; i++){
var number = num[i];
if (i % number == 0) {
switch (number[i]) {
case [0]:
output += out[0]
break;
case [1]:
output += out[1]
break;
}
if ( output == "" ) { output = i; }
val.innerHTML = (output);
}
}
</script>
</body>
</html>
You can use true as your switch condition.
Example:
switch (true) {
case (i % num[0] === 0) : output code; break;
case (i % num[1] === 0) : output code; break;
}
Also, it's worth noting that your structure here is possibly redundant:
if (i % number == 0) {
switch (i) {
case [0]: output += out[0]; break;
case [1]: output += out[1]; break;
}
}
It would be enough to have:
if (i % number == 0) {
output += out[i];
}

Try and catch for check sum validation on input to check three parts of an input in Javascript

Bouncing my head off the wall here trying to figure out a better way to handle this. I have a large input value which has three checks to check the sum of certain parts of the string in order to validate it. I'm using three try/catch blocks in one function to run the check right now and it seems to be working except for the final validation check which always seems to return true. What I'm wondering is a) is this a good method to use, b) is there a cleaner way to do this with for loop and c) why my final check is not doing anything. Any help is appreciated. I have access to jQuery and Underscore.js if that helps but I have not worked much with underscore. I made a fiddle here:
Sample Fiddle
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
// run the checksum
var valid = false;
try {
var sum = (parseInt(number[0]) * 7) +
(parseInt(number[1]) * 3) +
(parseInt(number[2])) +
(parseInt(number[3]) * 7) +
(parseInt(number[4]) * 3) +
(parseInt(number[5])) +
(parseInt(number[6]) * 7) +
(parseInt(number[7]) * 3) +
(parseInt(number[8]));
alert(((sum % 10).toFixed(0)));
var checkDigit = ((sum % 10).toFixed(0));
if ((number[9]) === ("" + checkDigit)) {
alert('Our Checkdigit is valid', checkDigit);
valid = true;
}
} catch (e) {
alert('Fail for check 1!');
valid = false;
}
try {
var sum2 = (parseInt(number[13]) * 7) +
(parseInt(number[14]) * 3) +
(parseInt(number[15])) +
(parseInt(number[16]) * 7) +
(parseInt(number[17]) * 3) +
(parseInt(number[18]));
alert(((sum2 % 10).toFixed(0)));
var checkDigit2 = ((sum2 % 10).toFixed(0));
if ((number[19]) === ("" + checkDigit2)) {
alert('Our Checkdigit2 is valid', checkDigit2);
valid = true;
}
} catch (e) {
alert('Fail for check 2!');
valid = false;
}
try {
var sum3 = (parseInt(number[21]) * 7) +
(parseInt(number[22]) *3) +
(parseInt(number[23])) +
(parseInt(number[24]) * 7) +
(parseInt(number[25]) * 3) +
(parseInt(number[26]));
alert(((sum3 % 10).toFixed(0)));
var checkDigit3 = ((sum3 % 10).toFixed(0));
if ((number[27]) === ("" + checkDigit3)) {
alert('Our Checkdigit3 is valid',checkDigit3);
valid = true;
}
} catch (e) {
valid = false;
}
alert('All Good DUde!');
return valid;
}
Here is the way to do it.
I have not thrown any error, only error can be if the number is not parseable and so you can throw it if you like else if your sum checks can validate that should be good enough
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
var valid = false;
//try{
var sum1 = returnSum(number,[0,1,2,3,4,5,6,7,8],[7,3,1,7,3,1,7,3,1]);
var sum2 = returnSum(number,[13,14,15,16,17,18],[7,3,1,7,3,1]);
var sum3 = returnSum(number,[21,22,23,24,25,26],[7,3,1,7,3,1]);
/*
//only if you are throwing err
}catch(e){
valid = false;
}
*/
if (number[9] === sum1 && number[19] === sum2 && number[27] === sum3) {
console.log(sum1 +'|' + sum2 + '|' + sum3);
valid = true;
}
console.log('All Good DUde!');
return valid;
}
function myParse(n){
return (isNaN(parseInt(n,10))) ? -1 : parseInt(n,10);
}
function returnSum(n,ind,mul){
var acc = 0;
var pNum = 0;
for(var i=0; i<ind.length; i++){
pNum = myParse(n[ind[i]]);
if(pNum == -1){
pNum=0;
//throw 'error';//if you really want to throw error on not a number / or your number should fail
}
acc += pNum * mul[i];
}
return (acc%10).toFixed(0)+'';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3> Sample test number to use -- copy and paste should work </p=h3>
<p>487013675311199070109160101300</p>
<input id="searchTxt" placeholder="add numbers together">
<div id='numberValue'>Number goes here</div>
Cheers. joy
From experience, you may want to separate as much math as possible in your try block. JavaScript has a weird way of handling variables and may not be doing what you think it is.

Categories