How to check if the input string consists of a word matches with the information from API in Javascript?

Viewed 96

Intended outcome: The user inputs any characters from the keyboard. They will then be used to check if the inputted string is a word from the Dictionary API. If they match with each other, the string will be in the <p> element. If not, then the inputted string will go through anotherFunction().

Questions:

  1. Is it possible by keyboard.event, but not in the <input> / <textarea>, for the fetchApi() to be able to search for a real word from a string, instead of each inputted character? (Like I do not want that only until the user types the word and press Enter, then the API starts kicking in)
  2. If so, what can I change in the code in order to get the above intended outcome?

Thank you again, and again. Thanks a lot!

var characters = '';
var text = document.getElementById("text");
var word = result[arg0].word;

document.addEventListener('keydown', function(input) {
  if (input.key >= 'a' && input.key <= 'z') {
    fetchApi(input.key);
  }
});

function fetchApi(word) {
  let url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
  fetch(url).then(res => res.json()).then(result => data(result, word));
  }

function data(result, word) {
  if (input.key == word) {
      characters += input.key;
      text.innerHTML = characters;
  }
  else {
      text.innerHTML = anotherFunction();
  }
}
<p id="text"></p>
1 Answers

I hope I understand your question right but I think what you want is:

  1. Only listen for key events in the input field instead of the entire document. For this simply add the event listener to the desired <input> or <textarea> instead of the document. Explained here
text.addEventListener('keydown', function(input) {
  if (input.key >= 'a' && input.key <= 'z') {
    fetchApi(input.key);
  }
});
  1. You can also listen for the Enter key. For this you could either simply get the value of the <input> and send it directly to the API (text.value). Or if you want to filter the characters before (and change as little code as possible from your existing solution) you could also send your characters string to it. (Like the code below)
let inputWord = ""
text.addEventListener('keydown', function(input) {
  if (input.key >= 'a' && input.key <= 'z') {
    inputWord += input.key; // add each character to string if it's between a-z
  } else if (input.key === "Enter") { // on enter fetch the entire inputWord
    fetchApi(inputWord);
    inputWord = "" // clear inputWord after Enter (but not in <input>)
  }
});
Related