Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

performing a search on enter?

I have this form:

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

I want to add an eventListener when I hit enter on the input(i.e. #locationsearch).
I tried doing this:

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

and this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Both are not console-logging.

What is the correct/better way to perform this action?

>Solution :

The onsubmit event would happen on the form itself, not the input. So you could use an id on the form instead to target it directly.

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading