在输入时执行搜索?

performing a search on enter?

我有这个表格:

<form>
  <label for="locationsearch">Location:</label>
  <input type="search" id="locationsearch" name="locationsearch" />
</form>

我想在输入(即#locationsearch)上按回车键时添加一个 eventListener。 我试过这样做:

const locationSearch = document.getElementById("locationsearch");
    locationSearch.addEventListener("search", () => {
      console.log("search entered");
    });

还有这个:

const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
  console.log("search entered");
};

两者都不是控制台日志记录。

执行此操作的 correct/better 方法是什么?

onsubmit 事件将发生在表单本身,而不是输入。因此,您可以在表单上使用 id 来直接定位它。

const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
  console.log("search entered");
};
<form id="locationsearch">
  <label for="locationsearch">Location:</label>
  <input type="search" name="locationsearch" />
</form>

您可以处理输入元素的 keydown 事件处理程序。如果按下 Enter 键,则检查键码。

const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keydown", (e) => {
  if (e.code === 'Enter') {
     // Do Something ? Search
  }
});

您可以为此使用 keypress 事件。

const locationSearch = document.getElementById("locationsearch");
    locationSearch.addEventListener("keypress", () => {
      if (event.key === "Enter") {
    event.preventDefault();
    let inputVal = document.getElementById("locationsearch").value;
    console.log("search entered "+inputVal);
    document.getElementById("locationsearch").value = "";
  }
});
<form>
  <label for="locationsearch">Location:</label>
  <input type="search" id="locationsearch" name="locationsearch" />
</form>