I have a simple search function that is misbehaving. The search box is inside of a form that we do not want to submit when searching, so I have the setup below.
$(function() {
jQuery.fn.onEnter = function(callback) {
this.keyup(function(e) {
if(e.keyCode == 13) {
e.preventDefault();
//e.stopPropagation();
if (typeof callback == 'function')
callback.apply(this);
}
});
return this;
}
$('#txtSearch').onEnter(function() {
search();
return false;
});
$('#search_btn').click(function() {
search();
return false;
});
function search() {
alert('searching');
}
});
The e.preventDefault() line isn’t working, so the search function fires as well as the form submits. I’ve tried it with both e.preventDefault() and e.stopPropagation() with no luck.
You are stopping the browser default
keyupevent notsubmitevent. Your best bet is to usekeydownso that the enter key itself is stopped.Also use
e.whichwhich is normalized for crossbrowser.You can try adding a keydown handler to prevent enter key and do stuff inside keyup.
DEMO: http://jsfiddle.net/PSkvm/1/