I would like to ask if someone finds out what the problem is in the code that I left of the game hanged.
I have a button with the id test-letter
, which the idea would be to go through an array where you save the word and compare it with the val()
of an input.
The problem is that something fails because it is not comparing it.
$(document).ready(function(){
//name = prompt('Cual es tu nombre');
//var h2Name = document.getElementById('name').innerHTML = name;
var words = ['pala','martillo','pico','pelota','guante', 'la'];
var answerWord = [];
var hiddenWord = [];
// function to pick a random word from words array
function pickWord() {
hiddenWord.pop();
var randomNumber = Math.floor(Math.random()* words.length);
var randomWord = words[randomNumber];
var divWord = $('.word-container');
var splitRandomWord = randomWord.split('');
hiddenWord.push(splitRandomWord);
divWord.html('');
for (var i = 0; i < randomWord.length; i++) {
var letter = answerWord[i] = '_';
divWord.append('<p class="letters">'+ letter + '</p>');
};
};
function resetArray(array) {
for (var i = 0; i < array.length; i++) {
array.pop();
}
}
$('#start').click(function(event) {
event.preventDefault();
resetArray(answerWord);
pickWord();
})
$('#test-letter').click(function(event) {
event.preventDefault();
var letterToTest = $('.guess').find('input').val();
if (letterToTest.length > 1) {
alert('Ingrese solo una letra')
} else if (letterToTest === '') {
alert('Debe ingresar una letra')
} else {
for (var i = 0; i < hiddenWord.length; i++) {
console.log(hiddenWord[i]);
console.log(letterToTest);
if (letterToTest === hiddenWord[i]) {
console.log('encontraste');
}
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="header">
<div class="border-header">
<h1>Ahorcado</h1>
<h2 id="name"></h2>
</div>
</div>
<div class="button-container">
<div>
<button id="start">Comenzar</button>
<button id="reset">Resetear</button>
</div>
</div>
<div class="word-container">
</div>
<div class="guess">
<input type="text" name="">
<button id="test-letter">Probar</button>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="script.js"></script>