Need help with Wiki Viewer Search using the Enter key

I’m working on my wikipedia viewer and searching using the search button works fine. You can type in your search text, click the search button and get results. However, I can’t get the search to work by hitting the enter key. In outputting some text to the console, it looks like the form is being submitted twice. I’ve tried to add e.preventDefault(); but it still doesn’t work. Any help would be much appreciated.

Link: https://codepen.io/shigginsdev/full/ALJgwG/

It might be better to change your html and js a bit:

  • instead of a button as “Search”, use input(type=submit)
  • remove the onClick handler
  • instead use: $("form").submit(onFormSubmit);
  • remove the event handler for the “Enter” keypress

.submit will get both a click on the submit button as well as a enter keypress.

EDIT:

That should be:
$("form").submit(function(e){ e.preventDefault(); onFormSubmit(); });

2 Likes

Yay!!! That did it. Thanks much!

What’s weird is that when I googled, the most common solution I found was the event handler for the enter key.

Hey thats cool Ben,

Is there a way to do that without jQuery.

( Being a tier 2 challenger i’m all about full vanilla now :grin:… Until I need functions like that anyway)

Works for all event types.
document.getElementById('form1').addEventListener('submit', function(e){ ... });

1 Like

excellent, thanks. :thumbsup: