Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not always returning false

This is the code I have. The console always reads wrong. What is happening. I think it is when I objectofy the textbox.

function compare() {
  var test = "test";
  var input = document.getElementById("input").value;
  var inputLen = input.length;
  var tick;
  for (tick = 0; tick < inputLen; tick++) {
    if (input[tick] != test[tick]) {
      break;
    }
  }
  if ((tick - 1) == test.length) {
    console.log("equal");
  } else {
    console.log("wrong");
  }
}
<input type="text" id="input" placeholder="text">
<input type="submit" id="submit" onclick="compare()">

I really could use some help. The console.log always returns "wrong".

like image 280
user3851290 Avatar asked Aug 29 '26 17:08

user3851290


1 Answers

While performing your for loop, the tick variable increases to 5 on the last iteration before exiting the loop. To resolve this, compare it to test.length without decreasing it with -1:

function compare() {
  var test = "test";
  var input = document.getElementById("input").value;
  var inputLen = input.length;
  var tick;
  for (tick = 0; tick < inputLen; tick++) {
    if (input[tick] != test[tick]) {
      break;
    }
  }
  // After exiting the loop, tick will be equal to 5, not 4.
  if (tick === test.length) {
    console.log("equal");
  } else {
    console.log("wrong");
  }
}
<input type="text" id="input" placeholder="text">
<input type="submit" id="submit" onclick="compare();">
like image 77
Koby Douek Avatar answered Aug 31 '26 08:08

Koby Douek