Need help with Wiki Viewer Search using the Enter key

Need help with Wiki Viewer Search using the Enter key
0

#1

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/


#2

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(); });


#3

Yay!!! That did it. Thanks much!


#4

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


#5

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)


#6

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


#7

excellent, thanks. :thumbsup: