dimanche 7 octobre 2018

something wrong with the if statement

I have a problem with the if function, it doesn't work the way that I want achieve . I'm trying to make the input do the following :

1) search result shouldn't show anything unless I type 3 letters at least.

2) if I type less than 3 letters and I press the "Enter key" on keyboard, it should show an alert.

in my code I only achieve one thing. show result after typing 3 letters if I added (event) to the function here is an example

function myFunction(event) {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  if (filter.length < 3 && event.key === "Enter") {
    alert(
      "Search is going to work only if the phrase contains at least 3 characters."
    );
  }
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

if I delete the (event) from function and typed less than 3 letters and pressed Enter , the alert show up. but it shows the search result after typing the first letter as well, here is an example of the same code without (event) :

function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  if (filter.length < 3 && event.key === "Enter") {
    alert(
      "Search is going to work only if the phrase contains at least 3 characters."
    );
  }
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

I want it to do both things in the same time :

1) search result shouldn't show anything unless I type 3 letters at least.

2) if I type less than 3 letters and I press the "Enter key" on keyboard, it should show an alert.

can someone tell me what am I doing wrong ?

Aucun commentaire:

Enregistrer un commentaire