简体   繁体   中英

Trigger a button with both Click and Enter key for fetching Javascript

I've been looking for different solutions on the site, but none seem to work for me. I need to trigger a submit button with Enter keypress event and mouse click, in order to fetch data from a weather api.

<div class="inputdiv">
    <input type="text" placeholder="Enter City, Country" id="cityinput">
    <input type="submit" value="Submit" id="add" onclick="">
</div>
<script src="./script.js"></script>

Here's the js:

let inputval = document.querySelector('#cityinput')
let btn = document.getElementById('add')

inputval.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
  event.preventDefault();
  document.getElementById("add").click();
      
     fetch('......')

When I press Enter it works, but I can't find a way to fetch even clicking the button.

The button is an input of type="submit" which by default triggers a page reload, either make it a <button> or keep it an <input type="submit" /> but then in this case you'll have do a event.preventDefault() followed by the desired logic.

You can put the inputs inside a form. Then enter will find first submit button and will trigger click

 let form = document.getElementById('form'); form.addEventListener('submit', (event) => { event.preventDefault(); console.log("Pressed") });
 <div class="inputdiv"> <form id="form"> <input type="text" placeholder="Enter City, Country" id="cityinput"> <input type="submit" value="Submit" id="add"> </form> </div>

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