Why the onclick only works if you click twice?

Tags: , ,



I was searching for autocomplete examples in pure javascript, and I found a pretty good example on JSFiddle, but it has a Bug that I’m trying to figure it out how to fix.

The autocomplete only autocompletes the text if you click at the paragraph twice

Code:

var db = [
  "drawLine",
  "drawCircle",
  "drawCircleMore",
  "fillLine",
  "fillCircle",
  "fillCircleMore"
];

function popupClearAndHide() {
  autocomplete_result.innerHTML = "";
  autocomplete_result.style.display = "none";
}

function updPopup() {
  if (!autocomplete.value) {
    popupClearAndHide();
    return;
  }
  var a = new RegExp("^" + autocomplete.value, "i");
  for (var x = 0, b = document.createDocumentFragment(), c = false; x < db.length; x++) {
    if (a.test(db[x])) {
      c = true;
      var d = document.createElement("p");
      d.innerText = db[x];
      d.setAttribute("onclick", "autocomplete.value=this.innerText;autocomplete_result.innerHTML='';autocomplete_result.style.display='none';");
      b.appendChild(d);
    }
  }
  if (c == true) {
    autocomplete_result.innerHTML = "";
    autocomplete_result.style.display = "block";
    autocomplete_result.appendChild(b);
    return;
  }
  popupClearAndHide();
}

autocomplete.addEventListener("keyup", updPopup);
autocomplete.addEventListener("change", updPopup);
autocomplete.addEventListener("focus", updPopup);
#autocomplete {
  border: 1px solid silver;
  outline: none;
  margin: 0;
  background: #fff;
}

#autocomplete_result {
  border: 1px solid silver;
  border-top: 0;
  position: absolute;
  overflow: auto;
  max-height: 93px;
  background: #fff;
}

#autocomplete,
#autocomplete_result {
  width: 200px;
  box-sizing: border-box;
}

#autocomplete,
#autocomplete_result p {
  padding: 4px;
  margin: 0;
  color: #000;
}

#autocomplete_result p:nth-child(2n+1) {
  background: #f6f6f6;
}

#autocomplete_result p:hover {
  background: #e5e5e5;
}
<input id="autocomplete" type="text" />
<div id="autocomplete_result" style="display: none;"></div>

Answer

On change event is trigger before the click event is able to complete

Removing the on change call would fix the issue. Great suggestion from the comment below to replace “keyup” event listener with “input” event listener. This would trigger on any input, not only typed.

Demo: https://jsfiddle.net/hexzero/qrwgh7pj/

    autocomplete.addEventListener("input", updPopup); 
    autocomplete.addEventListener("focus", updPopup); 


Source: stackoverflow