Search code examples
jquerykeypress

Enter key is not prevented with event.preventDefault()


I'm trying to prevent the use of the enter key inside inputs fields. I managed to do it for the backspace key so that my window does not close but it doesn't seem to work with the enter key. Why? Could it be because I unbind the keydown function?

$(document).unbind('keydown').bind('keydown', this.keyPress);

keyPress: function (event)
{
    var doPrevent = false;
    var d = event.srcElement || event.target;
    if ((d.tagName.toUpperCase() === 'INPUT' &&
                                                     (d.type.toUpperCase() === 'TEXT' ||
                                                         d.type.toUpperCase() === 'PASSWORD' ||
                                                         d.type.toUpperCase() === 'FILE' ||
                                                         d.type.toUpperCase() === 'EMAIL' ||
                                                         d.type.toUpperCase() === 'SEARCH' ||
                                                         d.type.toUpperCase() === 'DATE'))
                                                    || d.tagName.toUpperCase() === 'TEXTAREA') {

        if (event.keyCode === 8)
            doPrevent = d.readOnly || d.disabled;
        else if (event.keyCode == 13)
            doPrevent = true;
    }
    else
        doPrevent = true;
    if (doPrevent)
        event.preventDefault();
},

Solution

  • Nevermind, the code is working. If my window is still closing, it's because the enter key is connected to a different function, located in the backbone.modal.js

    Thanks!