-3

I'm trying to check if is true or false the letter I typed.

for exemplo, I have one String that I caught from a array doing join(' '):

"problem test javascript css pc"

My current code:

document.addEventListener('keydown', (event) => {

  let count = 0
  let charlist = "problem test javascript css pc"

for(let i = 0; i < charlist.length; i++){
  if(charlist[i] === event.key){
    count++
    console.log(count)
  }

}

 })

When I type "s" is counting 2, and when I type "t" is counting 3, there is no sequence..

What I need is check just the first letter "p" and count 1 return true, type letter "r" count 1 return true

how can I test this ?

SantGT5
  • 53
  • 4

2 Answers2

0

Here's an example you can follow. First you store the phrase as an array, and for every keydown, compare the event.key with the letter that matches the counter index of the phrase array. For each correctly keyed letter, you advance your counter. Look through this code to get an idea of how it works

let keycounter = 0,
  correct = 0,
  wrong = 0;
let response = document.querySelector('.response')
let completed = document.querySelector('.completed')
document.addEventListener('keydown', (event) => {

  let count = 0
  let charlist = "problem test javascript css pc";
   if (charlist.split('')[keycounter] === event.key) {
    completed.innerHTML += event.key
    correct++;
    keycounter++

    response.innerHTML = event.key + ' was correct';
  } else {
    wrong++;
    response.innerHTML = event.key + ' was wrong';
  }

  response.innerText += ' - ' + correct + ' right/' + wrong + ' wrong so far'

  if (correct === charlist.split('').length) response.innerText += +"<br> FINISHED";

})
.completed:empty, .response:empty{
display:none;
}

.completed, .response{
margin:5px 0;
padding:5px;
background:#f0f0f0;
}

.response{
color:#666;
}
<p>Click in this area and type in this phrase <strong>problem test javascript css pc</strong></p>

<div class='completed'></div>
<div class='response'></div>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

A different approach than @Kinglish's answer compares the string's current character using the current count.

let count = 0

document.addEventListener('keydown', (event) => {

  let mystring = "problem test javascript css pc"
  
  for(let i = count; i < mystring.length; i++){
    if(event.key == mystring.charAt(i)){
      console.log('correct character')
      count++
      break;
    }
    if (event.key != mystring.charAt(count+1)) {
      console.log('wrong character')
      break;
    } 
  }

})
<div>problem test javascript css pc</div>
<input style="margin-top: 10px;" class="typebox" placeholder="type here..."></div>
itsisaac19
  • 536
  • 3
  • 15