简体   繁体   中英

How to get enter key to emulate a button press?

I'm developing a weather app, and I only want the code to execute once the Enter key is pressed or when a user clicks on Submit. The problem is, the code executes whenever any key is pressed, and I'm not sure why? It wouldn't ordinarily be a big deal, but it's requesting the API every time and I only get 60 requests a minute, so two or three searches in that time will reach that limit.

let button = document.querySelector("#button");
let searchBox = document.querySelector("#search-box");
let city = document.querySelector(".city");
let feelsLike = document.querySelector(".feels-like");
let temperature = document.querySelector(".temp");
let weatherDescription = document.querySelector(".weather");
let windSpeed = document.querySelector(".wind");
let icons = document.querySelector(".icons");
searchBox.addEventListener("keypress", function (event) {
  if (event.key === "Enter") {
    document.getElementById("button").click();
  }
  fetch(
    "https://api.openweathermap.org/data/2.5/weather?q=" +
      searchBox.value +
      "&units=metric&appid="
  )

...Rest of code to be executed

)};

I think it would make sense for the enter key to emulate a button press, but I'm not entirely sure how to do that - and any resources I've used online haven't helped, unfortunately.

In your listener searchBox.addEventListener("keypress", function (event) {..} you're executing the fetch function everytime when a keypress occurs. Since the if -condition does not enclosure the your fetch execution.

Try this:

if (event.key === "Enter") {
    document.getElementById("button").click();
  
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
      searchBox.value +
      "&units=metric&appid="
    ) 
}

You should put the (fetch) logic in the click handler for the button.

Some other points:

  • If you need code to execute after you get the response from your fetch , then put that code in a chained then callback. Note that the promise that fetch returns, resolves to a response object, and you'll need to call one of its methods to get yet another promise back, which in turn will resolve to the actual data.
  • Don't call .click() . It is better to put the targeted code in a named function, and then call that function both here, and in the button's click handler.
  • You already had a variable for the button, so no need to call again getElemebtById .
function process() {
  fetch(
    "https://api.openweathermap.org/data/2.5/weather?q=" +
      searchBox.value +
      "&units=metric&appid="
  ).then(function (response) {
     return response.json(); // <-- maybe? or .text() ?
  }).then(function (data) {
     //...Rest of code to be executed
  });
});

button.addEventListener("click", process);

searchBox.addEventListener("keypress", function (event) {
  if (event.key === "Enter") process();
)};

As stated by Amacado, the fetch is outside the if.

Moreover, if the search box is actually an HTML <input type="search"> element, there is already an OnSearch event handler that takes account of both the enter key and the magnifying glass icon in the phone keyboard ( search event ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM