Help with Wikipedia Viewer, same function different results

Link to codepen: https://codepen.io/mdbeauche/pen/RygqNq/

I can’t understand why I’m getting the results that I am. I have a .on() handler for the input text field and for the search button. Both handlers call the exact same function with the exact same input which uses ajax to request data from Wikipedia and then clears the input text field.

If you enter in a search string and click the search button, the ajax request to Wikipedia is valid and returns data, but the text field doesn’t get cleared.

If you enter in a search string and press enter, the ajax request to Wikipedia returns an error, but the text field gets cleared.

Both events call the same function, with the same input. The function outputs the search URL sent in the Wikipedia ajax request to the console, and the URL is identical each time. Why am I getting different behavior (click = successful search but not clearing text field, press enter = unsuccessful search but text field cleared) and how can I fix it?

The input search box has a default behavior to go to another page or in your case, refresh the same page. It serves to send info via requests between sites. To prevent that behavior you need to put event.preventDefault(); inside the function that its event calls, in your case right below the if statement. To clear the input you only need to set it value to ’ '. Hope that helps you.

That did the trick, thank you very much for the help. Is there a better way to attach the same JavaScript function to a button as well as the text field pressing enter than what I’ve been doing?

I’m not very good at JQuery, i’m more a Vanilla JS kind of guy :grin:, but since JQuery is only a JS library, you can use any kind of event to trigger a function. See other kinds of inputs you can use as well on your pages to get different kinds of data.
There’s a lot of options you can use. Play around with events and inputs, see how they work and you’ll find whats work to do the job.