Reputation: 155
So I've read a lot about this but none of the resources I looked at solved my
specific issue.
Goal: When text is input into the box and enter is hit, I want the function $("#search").click();
to run
Problem: Instead, it seems to refresh the page.
I had a similar problem with the button, but that was solved with type="button"
. I've tried changing the type of the input to submit, text, search
, but no dice.
I tried
setting onsubmit="return false;"
in the input
tag and the parent form
tag and all combinations.
The code for the function:
$("#searchInput").keypress(function(e){
if(e.which == 13){
$("#search").click();
};
});
It is outside of the scope of the ajax request preceding it. I tried keyCode
as well.
EDIT: minified && EDIT#2 Previous edit broke the click functionality: Here is the fiddle: https://jsfiddle.net/bushido/ypxm0ukL/13/
Upvotes: 0
Views: 66
Reputation: 297
If you move the keypress handler out of onclick, and add preventDefault() to the keypress handler, it should work as desired:
$("#searchInput").keypress(function(e){
if(e.which == 13){
e.preventDefault();
$("#search").click();
};
});
Try this fiddle: https://jsfiddle.net/chestercharles/ypxm0ukL/12/
Upvotes: 1
Reputation: 567
Js fiddle here: https://jsfiddle.net/sav1q3wt/1/
The things I did:
1) Moved the keypress
event handler out of onclick
2) Changed onclick
to submit
and added e.preventDefault();
Edit:
preventDefault()
prevents default behaviour ex: redirecting after clicking a submit button
Upvotes: 1