Search code examples
jqueryhtmleventsjquery-on

jQuery.on('keydown') when key is "enter" is being intercepted (?) and won't work


I am modifying a substantial existing application. In this application, at the top of the page there is a search bar. I need to record when the user presses "Enter" in the search bar so that I can fire some logic.

Simple enough, it seems. I can just use jQuery keydown or even keypress event to record the key that is pressed and then if the key value matches 13 for "Enter" I can proceed.

<form action="https://www.google.com" method="get" target="_blank">
    <input id="search-field"/>
</form>

<script>
    $(document).on('keydown', "#search-field", function (e) {
        if (e.which == 13)
        {
            //"some logic"
        }
    });
</script>

This captures every keypress EXCEPT "enter"! When I create an alert(e.which); in my JavaScript, each key's value will pop up, but when it I try "enter" it just submits the form and loads a new page without triggering the alert.

My Question: Without knowing the existing code regarding the search-box (I have very little access) is there any way that I can somehow get this keydown event to fire? Why might it be failing?

Note: I have to use jQuery.on() in this format to handle the event


Solution

  • I didn't figure out how to circumvent the other events process. But I did find what was preventing my key from being recognized:

    In a file Site.js there was some JavaScript:

    $('#SearchTerm').keydown(function (event)
        {
            return handleKey(event);
        });
    
        $('#SearchTerm').keyup(function (event)
        {
            // Some stuff here...
            return false;
        }
    

    This file was included before the JavaScript file I had. Since it was first and had its own keydown/keyupevents, it was executing them and doing its own e.preventDefault() before the keypress had a chance to get to my own script.