Search code examples
javascriptjqueryfocuskeypress

How to get the html element id if user pressed enter inside textarea


There is much more code, but I will only show one function here:

$(window).keydown(function(event){
    if(event.keyCode == 13) {
        event.preventDefault();

        // how to check if a user pressed enter inside a specific
        // textarea box 
    }
});

Actually what I want to know is, is the specific element in focus or not!


Solution

  • You can simply check if your textarea is focused using the jQuery :focus selector :

    $(window).keydown(function(event){
        if(event.keyCode == 13) {
            event.preventDefault();
    
            if($('#yourTextarea').is(':focus')){
                //...
            }
        }
    });