Hey guys I am looking for a little help on how to get the enter key to trigger the search.
The way I have it now I am triggering the event with a button click and it works great.
When I try to put the anonymous “search” function inside a different function it does not work.
The reason I would like to do this is so that I can call the function with the button or key press events in a DRY way.
see my pens for example:
WORKING
NON-WORKING
Can anyone tell me why this does not work? If so can you point me to a good resource to read that would help me solve the problem?
You need to implement an event handler in jQuery to tell your code to search on pressing the enter key (not just when clicking the button. You can find some helpful information in the jQuery documentation - https://api.jquery.com/keypress/
@JamesRiall thank you so much for your quick reply. I have to apologize for the ambiguity. I do understand that I need to implement an event handler for the keypress, but the central issue is that the search function does not work when I put it into its own separate function and call that from the button click event handler as in the non working example. I could put the identical code in the call back for the keypress event but would like to avoid that as I think it is bad design because the effort is duplicated and not DRY(Don’t Repeat yourself).
You need to remove the parentheses in the method call like this:
$("#sub-btn").click(searchWiki);
@kblock-dev That worked like a charm… Thank you so much:thumbsup:. It definitely works now but I am a bit unclear as to why.
Some functions (ex. click event handlers) require a function as it’s parameter. It only requires the name of the function and handles the actual function call when the event is triggered. It could also be written like this:
$(’#btn-submit’).click (function (){
nameOfFunction();
});
Thanks for the insight… Looks like if A does not work then try B. I forget that in JS a function can behave like a variable too.