DEV Community

Cover image for Quick Javascript Tips 1: Easiest way to get enter key event with jQuery.
Rafael Melo
Rafael Melo

Posted on

Quick Javascript Tips 1: Easiest way to get enter key event with jQuery.

This the first of a series of quick tips that I’m using on the day-to-day coding with Javascript.

This one is about something really not cool that is getting the enter key event.

Let’s assume you have to build a search bar at the top of a website.

To make a search the user should press enter or click on the search button. That sounds easy. Since I’m using jQuery it’s something like this.

$('input').on('keypress', (event)=> {
        if(event.which === 13){
            //Do Something
        }
});
Enter fullscreen mode Exit fullscreen mode

That basically says: when the user types on the input, if the key he pressed has the code 13 (usually the enter key) do something.

If you test it on chrome it’ll work just fine. But when you test on an Android device, hell will come to earth: every key has code 229!

alt text
Every key has code 229!!

But don't despair! Here’s the thing: 229 is the key event that the browser emits when it’s processing what the user typed, and that happens a lot on Android because of auto-correct.

Because the auto-correct is processing the event to foresee what the user is typing, this piece of code won’t work because it’s always getting code 229 instead of each of the Key’s individual code... That’s not cool.

But to overcome this you can do the most native option with the widest support of every browser.

Wrap your search bar in a form tag.

Really simple and easy.

Just put everything inside a form tag...


<form>
    <input type="text">
    <button type="submit">
    Search!
    </button>
</form>
Enter fullscreen mode Exit fullscreen mode

...and deal with the submit event to do what you want!

$('form').on('submit', (event)=>{
    event.preventDefault();
    // Do what you want here
    // In this case get input value
    // Do a search
    // Redirect to results page
});
Enter fullscreen mode Exit fullscreen mode

Don’t forget to preventDefault(), so the page won’t refresh since it’s the native behavior. Also remember to put the button inside the form, so it will submit your data!

That’s it. This my first attempt to teach something so I hope I was able to tell it in a clear way.

See you in Quick Tip 2.

Top comments (0)