0

I'm trying to check if the inputted word is already inside of my array. SO for example, if someone enters 'cat' more than once an error message will display saying "cat has already been entered". I've tried a few different combinations of code but nothing I do seems to work. The findword function is what I have so far. Can someone take a look at my code and explain why its not working and provide a possible fix.

On another note, why doesn't the "word: empty" message pop up when the input field has been left blank?.

<body>
<input type="text" id=input></input>
<button onclick="addword()" class="button" type = "button">Add word</button><br><br>
<button onclick="start()" class="button" type = "button">Process word</button><br><br>
<p id="ErrorOutput"></p>
<p id="output"></p>
<p id="nameExists"></p>
</body>

.

var array = [];
return = document.getElementById("input").value;
function start() {
  var word = "word List";
  var i = array.length

  if (word.trim() === "") {
    word = "word: Empty"

  }
  document.getElementById('ErrorOutput').innerHTML = word
  while (i--) {
    document.getElementById('output').innerHTML = array[i] + "<br/>" +     document.getElementById('output').innerHTML;
  }

  var longestWord = {
    longword: '',len: 0};

  array.forEach(w => {
    if (longestWord.len < w.length) {
      longestWord.text = w;
      longestWord.len = w.length;
    }
  });

  document.getElementById('ErrorOutput').innerHTML = "The longest name in the array is " + longestWord.len + " characters";

}

function addword() {

  return = document.getElementById('input').value;
  array.push(return);


}

function findword() {
  var nameExists = array.indexOf(
      return) < 0 ?
    'The number ' +
    return +' does not exist in the array': 'The number ' +
      return +' exists in the array'

  document.getElementById('nameExists').textContent = nameExists
} 
ucMedia
  • 4,105
  • 4
  • 38
  • 46
Karl
  • 83
  • 1
  • 4
  • 9

1 Answers1

0

You can use array.indexOf(word) (command for your situation) to find the position of the word.

If the position is -1 the word is not inside the array.

More information on W3

Alex Logist
  • 41
  • 10