0

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.

3
  • Any reason to avoid setting it as the input's onclick? Commented Aug 16, 2022 at 9:31
  • Have a look at this [fiddle][1] you can call a certain function onClick and inside your listener [1]: jsfiddle.net/L2reck04 Commented Aug 16, 2022 at 9:33
  • wrap your form inputs with <form> tag, add button with type='submit' attribute. Then attach submit even listener to your form using JS and call e.preventDefault() to prevent default behavior.. Commented Aug 16, 2022 at 9:36

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.