Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery preventDefault Not Behaving

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.

like image 851
Cory Dee Avatar asked May 03 '26 04:05

Cory Dee


1 Answers

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;
}
like image 67
Selvakumar Arumugam Avatar answered May 04 '26 19:05

Selvakumar Arumugam