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 keyup event not submit event. Your best bet is to use keydown so that the enter key itself is stopped.
Also use e.which which 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/
jQuery.fn.onEnter = function(callback) {
this.keyup(function(e) {
if(e.keyCode == 13) {
//e.stopPropagation();
if (typeof callback == 'function')
callback.apply(this);
}
}).keydown(function (e) {
if(e.keyCode == 13) {
e.preventDefault();
}
});
return this;
}
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