Search code examples
javascripthtmlif-statementstring-comparison

Im trying to compare two variable in javascript


It will have one of the variables defined and the other is defined when you typed if what you typed is the same it has the variable it says correct word and if they are not the same it says an incorrect word. My problem is that always say an incorrect word

function wordcompare() {
  var word1 = "word";
  var typed = document.getElementById("word");

  if (typed === word1) {
    alert("Correct word");
  } else {
    alert("Incorrect word");
  }
}

Solution

  • So, I'm assuming you have an input element, and a button, and when you click the button it calls the function to make the comparison.

    You need to get the value from the input element, otherwise you're just returning the element, and you can't make a comparison with that.

    // Cache the elements
    const input = document.querySelector('input');
    const button = document.querySelector('button');
    
    // When the button is clicked call the function
    button.addEventListener('click', wordCompare, false);
    
    function wordCompare() {
    
      const word1 = 'word';
    
      // Get the value from the input element and
      // then make the comparison
      if (input.value === word1) {
        console.log('Correct word');
      } else {
        console.log('Incorrect word');
      }
    }
    <input />
    <button>Check word</button>