So, I'm coding out a hangman style game as is the custom when learning how to user JS. I have it working pretty well, but I cannot seem to figure out how to properly identify and prevent duplicate wrong guesses.
Example: if you press "f" and it is not in the word, display and decrement the remaining scores once, and if you press "f" again, ignore the input. Here is my code thus far. I have my existing code in the function but it doesn't currently do anything. Any advice is appreciated.
// words to guess will be selected from here
var wordSelectionArray = [
"adventure", "bandit", "battleaxe", "battlefield", "beholder", "bugbear", "castle", "catapult", "cleric", "dragon", "dungeon",
"fairy", "fireball", "giant", "goblin", "knight", "magic", "monster", "necromancer", "owlbear", "paladin", "potion", "quarterstaff",
"sorcerer", "spells", "sword", "vampire", "warlock", "wizard", "zombie"]
//variable to hold the randomly selected word
var selectedWord = "";
//variable to store number of blanks
var blanks = 0;
//var to hold the split out array of the randomly selected word.
var letters = [];
//var to store blanks with the correct word
var blankAndCorrect = [];
//var to hold the incorrect letter guesses when input by the user.
var wrongGuess = [];
// start the game with a score of zero
var wins = 0;
var losses = 0;
//variable to hold number of guesses remaining
var guessesRemaining = 12;
//array for guessed letters
var alreadyGuessedLetters = [];
//variable to hold the background music
var myMusic = document.getElementById("background-music");
function game() {
selectedWord = wordSelectionArray[Math.floor(Math.random() * wordSelectionArray.length)];
letters = selectedWord.split("");
blanks = selectedWord.length;
for (var i = 0; i < blanks; i++) {
blankAndCorrect.push("_");
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
myMusic.play();
// console.log(selectedWord);
// console.log(letters);
// console.log(blanks);
// console.log(blankAndCorrect);
};
//function to start the game over
function reset() {
guessesRemaining = 12;
wrongGuess = [];
blankAndCorrect = [];
game();
};
//check and compare function
function checkInput(letter) {
letterInWord = false;
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
letterInWord = true;
}
} if (letterInWord) {
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
blankAndCorrect[i] = letter;
}
}
} if (letterInWord) {
for (var i = 0; i < alreadyGuessedLetters.length; i++) {
if (selectedWord[i] !== letter) {
alreadyGuessedLetters[i] = letter;
return;
}
}
} else {
wrongGuess.push(letter);
alreadyGuessedLetters.push(letter);
guessesRemaining--;
console.log(alreadyGuessedLetters);
}
};
//function to check wins/losses
function completeGame () {
if (letters.toString() == blankAndCorrect.toString()) {
wins++;
document.getElementById("correct-answer-message").innerHTML = "Great Job! " + selectedWord.toLocaleUpperCase() + " was the word!" ;
reset();
document.getElementById("wins").innerHTML = " " + wins;
} else if (guessesRemaining === 0) {
losses++;
reset();
document.getElementById("losses").innerHTML = " " + losses;
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
document.getElementById("guesses-remaining").innerHTML = " " + guessesRemaining;
};
game();
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
checkInput(guesses);
completeGame();
// console.log(guesses);
document.getElementById("letters-guessed").innerHTML = " " + wrongGuess.join(" ");
}
See how I'm ignoring duplicates in checkInput.
// words to guess will be selected from here
var wordSelectionArray = [
"adventure", "bandit", "battleaxe", "battlefield", "beholder", "bugbear", "castle", "catapult", "cleric", "dragon", "dungeon",
"fairy", "fireball", "giant", "goblin", "knight", "magic", "monster", "necromancer", "owlbear", "paladin", "potion", "quarterstaff",
"sorcerer", "spells", "sword", "vampire", "warlock", "wizard", "zombie"]
//variable to hold the randomly selected word
var selectedWord = "";
//variable to store number of blanks
var blanks = 0;
//var to hold the split out array of the randomly selected word.
var letters = [];
//var to store blanks with the correct word
var blankAndCorrect = [];
//var to hold the incorrect letter guesses when input by the user.
var wrongGuess = [];
// start the game with a score of zero
var wins = 0;
var losses = 0;
//variable to hold number of guesses remaining
var guessesRemaining = 12;
//array for guessed letters
var alreadyGuessedLetters = [];
//variable to hold the background music
var myMusic = document.getElementById("background-music");
function game() {
selectedWord = wordSelectionArray[Math.floor(Math.random() * wordSelectionArray.length)];
letters = selectedWord.split("");
blanks = selectedWord.length;
for (var i = 0; i < blanks; i++) {
blankAndCorrect.push("_");
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
// myMusic.play();
// console.log(selectedWord);
// console.log(letters);
// console.log(blanks);
// console.log(blankAndCorrect);
};
//function to start the game over
function reset() {
guessesRemaining = 12;
wrongGuess = [];
blankAndCorrect = [];
game();
};
//check and compare function
function checkInput(letter) {
if (wrongGuess.includes(letter)) { // <--- HERE
// do anything else you wanna do
return;
}
letterInWord = false;
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
letterInWord = true;
}
} if (letterInWord) {
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
blankAndCorrect[i] = letter;
}
}
} if (letterInWord) {
for (var i = 0; i < alreadyGuessedLetters.length; i++) {
if (selectedWord[i] !== letter) {
alreadyGuessedLetters[i] = letter;
return;
}
}
} else {
wrongGuess.push(letter);
alreadyGuessedLetters.push(letter);
guessesRemaining--;
console.log(alreadyGuessedLetters);
}
};
//function to check wins/losses
function completeGame () {
if (letters.toString() == blankAndCorrect.toString()) {
wins++;
document.getElementById("correct-answer-message").innerHTML = "Great Job! " + selectedWord.toLocaleUpperCase() + " was the word!" ;
reset();
document.getElementById("wins").innerHTML = " " + wins;
} else if (guessesRemaining === 0) {
losses++;
reset();
document.getElementById("losses").innerHTML = " " + losses;
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
document.getElementById("guesses-remaining").innerHTML = " " + guessesRemaining;
};
game();
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
checkInput(guesses);
completeGame();
// console.log(guesses);
document.getElementById("letters-guessed").innerHTML = " " + wrongGuess.join(" ");
}
<div id="current-word"></div>
<div id="guesses-remaining"></div>
<div id="letters-guessed"></div>
Related
This is my first post. I'm new to coding and one of my projects is to create a simple version of Blackjack using Javascript. I made a basic website for it here and I've encountered a problem. The dealer occasionally gets dealt 3 or more cards. The dealer should always have 2 cards. (unless you hit or stay.) Adding cards to the dealer like the player isn't required so I did not write code for it. I have the dealer sum limit set to 13 (I've tried lower/higher numbers, but that doesn't really "fix" the issue.") and also edited the for loops. I thought it could be an array problem. Perhaps I have the arrays too simplified and need to rename the cards?
Here is my code any help or tips would be appreciated!
var dealerSum = 0;
var yourSum = 0;
var dealerAceCount = 0;
var yourAceCount = 0;
var hidden;
var deck;
var canHit = true;
window.onload = function () {
buildDeck()
shuffleDeck()
startGame()
}
function buildDeck() {
let values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
let types = ["C", "D", "H", "S"]
deck = []
for (let i = 0; i < types.length; i++) {
for (let j = 0; j < values.length; j++) {
deck.push(values[j] + "-" + types[i]);
}
}
// console.log(deck);
}
function shuffleDeck() {
for (let i = 0; i < deck.length; i++) {
let j = Math.floor(Math.random() * deck.length);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
// console.log(deck);
}
function startGame() {
hidden = deck.pop();
dealerSum += getValue(hidden);
dealerAceCount += checkAce(hidden);
// console.log(hidden);
// console.log(dealerSum);
while (dealerSum < 13) {
let cardImg = document.createElement("img");
let card = deck.pop();
cardImg.src = "./cards/" + card + ".png";
dealerSum += getValue(card);
dealerAceCount += checkAce(card);
document.getElementById("dealer-cards").append(cardImg);
}
console.log(dealerSum)
for (let i = 0; i < 2; i++) {
let cardImg = document.createElement("img");
let card = deck.pop();
cardImg.src = "./cards/" + card + ".png";
yourSum += getValue(card);
yourAceCount += checkAce(card);
document.getElementById("your-cards").append(cardImg);
}
console.log(yourSum);
document.getElementById("refresh").addEventListener("click", refresh);
document.getElementById("hit").addEventListener("click", hit);
document.getElementById("stay").addEventListener("click", stay);
}
function hit() {
if (!canHit) {
return;
}
let cardImg = document.createElement("img");
let card = deck.pop();
cardImg.src = "./cards/" + card + ".png";
yourSum += getValue(card);
yourAceCount += checkAce(card);
document.getElementById("your-cards").append(cardImg);
if (reduceAce(yourSum, yourAceCount) > 21) {
canHit = false;
}
}
function stay() {
dealerSum = reduceAce(dealerSum, dealerAceCount);
yourSum = reduceAce(yourSum, yourAceCount);
canHit = false;
document.getElementById("hidden").src = "./cards/" + hidden + ".png";
let message = "";
if (yourSum > 21) {
message = "You lose! Better luck next time. Refresh to try again!"
}
else if (dealerSum > 21) {
message = "You win! Refresh to play again!"
}
else if (yourSum == dealerSum) {
message = "Tie! Refresh to play again!";
}
else if (yourSum > dealerSum) {
message = "You win! Refresh to play again!";
}
else if (yourSum < dealerSum) {
message = "You lose! Better luck next time. Refresh to play again!";
}
document.getElementById("dealer-sum").innerText = dealerSum;
document.getElementById("your-sum").innerText = yourSum;
document.getElementById("result").innerText = message;
}
function refresh() {
window.location.reload();
}
function getValue(card) {
let data = card.split("-");
let value = data[0];
if (isNaN(value)) {
if (value == "A") {
return 11;
}
return 10;
}
return parseInt(value);
}
function checkAce(card) {
if (card[0] == "A") {
return 1;
}
return 0;
}
function reduceAce(playerSum, playerAceCount) {
while (playerSum > 21 && playerAceCount > 0) {
playerSum -= 10;
playerAceCount -= 1;
}
return playerSum;
}
var secretWord = [];
var underScoreWord = [];
var wins = 0;
var guessesRemaining = 10;
var alreadyGuessed = [];
var wordLetter = true;
//Assign HTML elements to variables
var cityText = document.getElementById("city-text");
var winsNum = document.getElementById("wins-num");
var guessesNum = document.getElementById("guesses-num")
var lettersGuessed = document.getElementById("letters-guessed")
//Array of cities
var city = ["Paris", "Wellington", "Hanoi", "Perth", "Marseille", "London", "Ottawa", "Zurich", "Boston", "Tokyo", "Detroit"];
//console.log(city);
//Pick random word from the team array and push the result to an empty array.
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord = randomCity.split('');
return randomCity;
}
var cityPicked = pickRandomCity();
//Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
console.log('secretWord : ' + secretWord);
// console.log('underScoreWord : ' + underScoreWord);
// console.log('------------------');
// console.log('cityPicked : ' + cityPicked);
//Check for letters
//Listen for key press and check to see if its a match
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
for (var j = 0; j < secretWord.length; j++) {
if (userGuess.toUpperCase() === secretWord[j].toUpperCase()) {
wordLetter = true;
underScoreWord[j] = userGuess;
guessesRemaining--;
}
else if (!wordLetter) {
alreadyGuessed.push();
// guessesRemaining--;
}
}
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
}
Does anybody know how can I push userGuess to an empty array and then display? As you can see I managed to push the userGuess to the alreadyGuessed array but it only displays one character at a time on the page.
The end goal is for the alreadyGuessed array to display like this - Letters alreadyGuessed: a g r h e t
You can store what keys have been pressed with an object, and at the beginning of each keyup event, check if user has pressed it.
I also switched the for loop to map
var guessedLetters = {};
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
alreadyGuessed.push(userGuess.toUpperCase());
guessedLetters[userGuess.toUpperCase()] = true;
guessesRemaining--;
} else { // this key has been pressed before, dont do anything
return;
}
secretWord.map((n, i) => {
if (userGuess.toUpperCase() === n.toUpperCase()) {
underScoreWord[i] = n;
}
})
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
}
Looks like wordLetter is a global variable initialized to true. Also looks like it is never set to false so your call to alreadyGuessed.push(userGuess); will never be reached since !wordLetter is always false.
Try alreadyGuessed.push(userGuess); inside your event listener's elseif statement.
EDIT:
As per the suggestion from #foxinatardis, the way you modify and check for wordLetter inside your loop needs to be changed:
if (userGuess.toUpperCase() === secretWord[j].toUpperCase()) {
wordLetter = true;
underScoreWord[j] = userGuess;
guessesRemaining--;
} else {
wordLetter = false;
alreadyGuessed.push(userGuess);
// guessesRemaining--;
}
You actually don't need the wordLetter variable anymore with this change, unless you're using it elsewhere for something else.
At this current moment I've been trying to work through an issue I've had with my Hangman JS game. I've spent the last week attempting to replace "underscores", which I have as placeholders for the current secret word. My idea was to loop through the correctLettersOUT, and wherever that particular letter exists in the placeholder would replace it with said letter. This small part of my code below is where the issue is I believe, but I have also created a function in my whole code if a new function necessary.
Any advice is appreciated.
function startGame() {
var testWord = document.getElementById("randTest").innerHTML = secretWord;
var correctLettersOUT = "";
document.getElementById("currentGuess").innerHTML = secretBlanks(secretWord)
function secretBlanks(secretWord) {
for (var i = 0; i < secretWord.length; i++) {
correctLettersOUT += ("_ ");
}
return correctLettersOUT;
}
}
The snippet of my JS is below, it may be large but all of it is necessary. If you wish to view the whole code in it's entirety, the link is CodePen Link.
var guessWords = ["school", "test", "quiz", "pencil", "ruler", "protractor", "teacher", "homework", "science", "math", "english", "history", "language", "elective", "bully", "grades", "recess", ];
var secretWord = guessWords[Math.floor(Math.random() * guessWords.length)];
var wrongLetters = [];
var correctLetters = [];
var repeatLetters = [];
var guesses = Math.round((secretWord.length) + (.5 * secretWord.length));
var correctLettersOUT = "";
function startGame() {
var testWord = document.getElementById("randTest").innerHTML = secretWord;
var correctLettersOUT = "";
document.getElementById("currentGuess").innerHTML = secretBlanks(secretWord)
function secretBlanks(secretWord) {
for (var i = 0; i < secretWord.length; i++) {
correctLettersOUT += ("_ ");
}
return correctLettersOUT;
}
}
function correctWord() {
var guessLetter = document.getElementById("guessLetter").value;
document.getElementById("letter").innerHTML = guessLetter;
for (var i = 0; i < secretWord.length; i++) {
if (correctLetters.indexOf(guessLetter) === -1)
{
if (guessLetter === secretWord[i]) {
console.log(guessLetter === secretWord[i]);
correctLettersOUT[i] = guessLetter;
correctLetters.push(guessLetter);
break;
}}
}
if (wrongLetters.indexOf(guessLetter) === -1 && correctLetters.indexOf(guessLetter) === -1) {
wrongLetters.push(guessLetter);
}
console.log(correctLetters); //Used to see if the letters were added to the correct array**
console.log(wrongLetters);
wordGuess();
}
function wordGuess() {
if (guessLetter.value === '') {
alert("You didn't guess anything.");
} else if (guesses > 1) {
// Counts down.
guesses--;
console.log('Guesses Left: ' + guesses);
// Resets the input to a blank value.
let guessLetter = document.getElementById('guessLetter');
guessLetter.value = '';
} else {
console.log('Game Over');
}
//console.log(guesses)
}
function replWord() { }
One solution to see if the word has been guessed completely and create the partially guessed display with the same info, is to keep a Set with the not yet guessed letters, initialized at game start unGuessed = new Set(secretWord);
Since the Set's delete method returns true if the letter was actually removed (and thus existed), it can be used as a check if a correct letter was entered.
Subsequently, the display can be altered in a single place (on startup and after guessing), by mapping the letters of the word and checking if the letter is already guessed:
function alterDisplay(){
document.getElementById("currentGuess").innerHTML =
[...secretWord].map(c=>unGuessed.has(c) ? '_' : c).join(' ');
}
Some mockup code:
let guessWords = ["school", "test", "quiz", "pencil", "ruler", "protractor", "teacher", "homework", "science", "math", "english", "history", "language", "elective", "bully", "grades", "recess", ],
secretWord, unGuessed, guesses;
function startGame() {
secretWord = guessWords[Math.floor(Math.random() * guessWords.length)];
guesses = Math.round(1.5 * secretWord.length);
unGuessed = new Set(secretWord);
setStatus('');
alterDisplay();
}
function alterDisplay(){
document.getElementById("currentGuess").innerHTML = [...secretWord].map(c=>unGuessed.has(c) ? '_' : c).join(' ');
}
function setStatus(txt){
document.getElementById("status").innerHTML = txt;
}
function correctWord() {
let c= guessLetter.value[0];
guessLetter.value = '';
if (!c) {
setStatus("You didn't guess anything.");
}
else if(unGuessed.delete(c)){
alterDisplay();
if(!unGuessed.size) //if there are no unguessed letters left: the word is complete
setStatus('Yep, you guessed it');
}
else if(--guesses < 1){
setStatus('Game Over!');
}
else
setStatus('Guesses Left: ' + guesses);
}
startGame();
let gl = document.getElementById("guessLetter");
gl.onkeyup= correctWord; //for testing: bind to keyup
gl.value = secretWord[1];correctWord(); //for testing: try the 2nd letter on startup
<div id=currentGuess></div>
<input id=guessLetter><span id=letter></span>
<div id='status'></div>
I'm working on an ordering application that needs to allow for the user to remove a previously entered order. The 'Remove' button currently removes all output from the screen, and when a new order is added, all past orders and the new order reappear, rather than the single new order.
// Global Variables
var orderTotal = 0;
var grandTotal = 0;
var burritos = [];
function init() {
var btnAddToOrder = document.getElementById("addToOrder");
btnAddToOrder.onclick = processOrder;
}
function processOrder() {
var fieldBurrito = document.getElementById("burrito");
var index = fieldBurrito.selectedIndex;
var burritoChoice = fieldBurrito.options[index].value;
var fieldRice = document.getElementsByName("rice");
for (var a = 0; a < fieldRice.length; a++) {
if (fieldRice[a].checked) {
var riceChoice = fieldRice[a].value;
} else {
riceChoice = "No";
}
}
var fieldBeans = document.getElementsByName("beans");
for (var e = 0; e < fieldBeans.length; e++) {
if (fieldBeans[e].checked) {
var beansChoice = fieldBeans[e].value;
} else {
beansChoice = "No";
}
}
var fieldSalsa = document.getElementsByName("salsa");
var salsaChoice = "";
for (var i = 0; i < fieldSalsa.length; i++) {
if (fieldSalsa[i].checked) {
salsaChoice += fieldSalsa[i].value + " ";
}
}
var fieldGuac = document.getElementsByName("guacamole");
for (var o = 0; o < fieldGuac.length; o++) {
if (fieldGuac[o].checked) {
var guacChoice = fieldGuac[o].value;
} else {
guacChoice = "No Guac";
}
}
//Reset the cost of each individual order
orderTotal = 0;
grandTotal = 0;
//Determine the type of burrito and associate correct cost
switch (burritoChoice) {
case "Chicken":
orderTotal += 6.20;
break;
case "Steak":
orderTotal += 6.75;
break;
case "Carnitas":
orderTotal += 6.60;
break;
case "Sofritas":
orderTotal += 6.20;
break;
case "Barbacoa":
orderTotal += 6.60;
break;
}
if (guacChoice == "Guacamole") {
orderTotal += 1.40;
}
var burritoInstance = {
"Burrito":burritoChoice,
"Rice":riceChoice,
"Beans":beansChoice,
"Salsa":salsaChoice,
"Guacamole":guacChoice,
"Price":orderTotal
};
burritos.push(burritoInstance);
// Check to see that the fieldValues array has at least one element
if (burritoChoice !== "Choose a Burrito") {
generateReceipt(burritos);
} else {
console.log("Please choose a burrito type to continue. All other toppings are optional.");
}
}
//********************************************************************************************
function removeButton(i) {
var removeButton = document.createElement("button");
var value = document.createTextNode("Remove Order");
removeButton.appendChild(value);
removeButton.id = i;
removeButton.onclick = function() {
var thing = this.parentNode;
thing.parentNode.removeChild(thing);
}
return removeButton;
}
//--------------------------------------------------------------------------------------------
function br() {
return document.createElement('br');
}
//********************************************************************************************
function generateReceipt(burritos) {
var element = document.getElementById("output");
if(element) {
element.parentNode.removeChild(element);
}
var burritoList = document.createElement("div");
burritoList.id = "output";
for(var i=0; i < burritos.length; i++) {
var outputList = document.createTextNode(burritos[i].Burrito + " Burrito - " +
burritos[i].Rice + " Rice - " +
burritos[i].Beans + " Beans - " +
burritos[i].Salsa + " Salsa - " +
burritos[i].Guacamole + " - $" +
burritos[i].Price);
outputList.id = "burritoInstance";
grandTotal += burritos[i].Price;
burritoList.appendChild(outputList);
burritoList.appendChild(removeButton(i));
burritoList.appendChild(br());
}
var orderTotal = document.createTextNode("Order Total: $" + grandTotal);
burritoList.appendChild(orderTotal);
document.body.appendChild(burritoList);
}
At some point I will need to include logic in the button click to adjust the order total when an order is removed, but first I need to be able to access the order preceding each button.
JSFiddle
I have a function that performs a Luhn check on a card entry when a form is posted.
<script language="javascript">
function Calculate(Luhn)
{
var sum = 0;
for (i=0; i<Luhn.length; i++ )
{
sum += parseInt(Luhn.substring(i,i+1));
}
var delta = new Array (0,1,2,3,4,-4,-3,-2,-1,0);
for (i=Luhn.length-1; i>=0; i-=2 )
{
var deltaIndex = parseInt(Luhn.substring(i,i+1));
var deltaValue = delta[deltaIndex];
sum += deltaValue;
}
var mod10 = sum % 10;
mod10 = 10 - mod10;
if (mod10==10)
{
mod10=0;
}
return mod10;
}
function Validate(Luhn)
{
var LuhnDigit = parseInt(Luhn.substring(Luhn.length-1,Luhn.length));
var LuhnLess = Luhn.substring(0,Luhn.length-1);
if (Calculate(LuhnLess)==parseInt(LuhnDigit))
{
return true;
}
alert("\n\nYou have mis-typed your card number! \nPlease check and correct.\n\n")
return false;
}
I also have a function that removes any spaces that may have been entered in the card number onblur.
function stripChar(sValue, sChar) {
var i, tempChar, buildString;
buildString = ""
for (var i=0; i<sValue.length; i++) {
tempChar = sValue.charAt(i);
if (tempChar != sChar) {
buildString = buildString + tempChar;
}
}
return buildString;
How do I combine the functions so that the spaces are removed and the card number checked onblur.
In your onblur function you could use:
Validate(stripChar(sValue, sChar));