搜索按 Enter 提交

问题描述 投票:0回答:2

我试图让我的搜索栏在按 Enter 键时正常工作。按下按钮时有效,但按下 Enter 时无效......

/**
 * search toggle
 */

const searchTogglers = document.querySelectorAll("[data-search-toggler]");
const searchBox = document.querySelector("[data-search-box]");

for (let i = 0; i < searchTogglers.length; i++) {
  searchTogglers[i].addEventListener("click", function () {
    searchBox.classList.toggle("active");
  });
}
<div class="search-container" data-search-box>
    <div class="input-wrapper">
      <input type="search" id="search" autocomplete="off"  aria-label="search" placeholder="Search here..." class="search-field">
    <button class="search-submit" type="submit" id="button" onclick="openPage(event)" value="Chercher" aria-label="submit search" data-search-toggler>
        <ion-icon name="search-outline"></ion-icon>
      </button>
      <button class="search-close" aria-label="close search" data-search-toggler></button>
    </div>
  </div>

javascript search click enter
2个回答
0
投票

只需包裹在表单元素中

document.getElementById("searchForm").addEventListener("submit", (e) => {
  e.preventDefault();
  console.log(document.getElementById("search").value)
})
<div class="search-container" data-search-box>
  <form id="searchForm">
    <div class="input-wrapper">
      <input type="search" id="search" autocomplete="off" aria-label="search" placeholder="Search here..." class="search-field">
      <button class="search-submit" type="submit" id="button" value="Chercher" aria-label="submit search" data-search-toggler>
        <ion-icon name="search-outline">Search</ion-icon>
      </button>
      <button type="button" class="search-close" aria-label="close search" data-search-toggler>Close</button>
    </div>
  </form>
</div>


0
投票

在搜索框上使用按键事件。

/**
 * search toggle
 */

const searchTogglers = document.querySelectorAll("[data-search-toggler]");
const searchBox = document.querySelector("[data-search-box]");

for (let i = 0; i < searchTogglers.length; i++) {
  searchTogglers[i].addEventListener("click", function () {
    searchBox.classList.toggle("active");
  });
}
searchBox.addEventListener("keypress", function (e) {
  if(e.key === 'Enter'){
     console.log('Search :',e.target.value);
  }
});
<div class="search-container" data-search-box>
    <div class="input-wrapper">
      <input type="search" id="search" autocomplete="off"  aria-label="search" placeholder="Search here..." class="search-field">
    <button class="search-submit" type="submit" id="button" onclick="openPage(event)" value="Chercher" aria-label="submit search" data-search-toggler>
        <ion-icon name="search-outline"></ion-icon>
      </button>
      <button class="search-close" aria-label="close search" data-search-toggler></button>
    </div>
  </div>

© www.soinside.com 2019 - 2024. All rights reserved.