I am in a big problem. In my website, I am using a search box. When click/enter press on the search result will redirect to the specific page. I also given a hide() of search results when click on other parts of window. The problem is, when I press Enter key over a result, it execute the click function and remove the search output window content. I only need to clear the search result on mouse click.
This is my click event code
$(document).click(function (e) {
if (!$(e.target).is('#search_result')) {
$("#search_result").hide();
$("#search_result").html("");
}
});
and my enter event is
function TriggerSearch(e) {
var search_string = $("#search").val();
e = e || window.event;
var keycode;
if (window.event) {
keycode = e.which ? window.event.which : window.event.keyCode;
}
var key = e.which;
switch (key) {
case 38:
break;
case 40:
break;
case 13:
search_product();
break;
default:
default function();
}
}
The call to TriggerSearch is
$("#search").keyup(TriggerSearch);
These 3 parts contain the work flow. When press an Enter, rather than go to the search_product() function, it execute the click event. It did not enter to the search_product() function. As per my knowledge, when a click event occur on #search, then it will go to the TriggerSearch() function and if it is 13, then execute the search_product() function. I can't understand why this not happening.
How can I prevent to execute the click event on pressing Enter key?
preventdefault() should do the trick (as you are passing the standard event object to TriggerSearch via the keyup event). Update: You have to use the keypressevent instead of keyup as it is the one that triggers a form submit.
case 13:
e.preventDefault();
search_product();
If not, please post the rest of the code :)
The problem is that the default form submission is triggered on keypress, not keyup. I changed it to use keypress instead and the preventDefault (capital D, sorry) now works:
function search_product() {
alert("search_product()");
}
function TriggerSearch(e) {
var search_string = $("#search").val();
e = e || window.event;
var keycode;
if (window.event) {
keycode = e.which ? window.event.which : window.event.keyCode;
}
var key = e.which;
switch (key) {
case 38:
break;
case 40:
break;
case 13:
e.preventDefault();
search_product();
break;
default:
break;
}
}
$("#search").keypress(TriggerSearch);
To test, comment out e.preventDefault(); in the JSFiddle and the page will then try to submit on Enter.
Based on comments below I should clarify that the submit action I mentioned does not relate to the submit button, but the form. This example has no submit, but does what is wanted.
Note: I had to remove your default function() as it gave an error.
What is that supposed to do?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With