Hezerac Hezerac - 2 months ago 11
jQuery Question

jquery focus on an input using keydown

If an input is unfocused, how to focus on it just by hitting the enter key.(theres no button or anything else involved. just one input.)

For example something like:

$(!("input").focus().keydown(function(e){
if(e.which == 13) {
$("#input").focus();
}
});


Edit:
Went with ehsan's approach, slightly modified:

if(e.which == 13 && $(document.activeElement).not("#user-input")) {
$("#user-input").focus();
}

Answer

Try this :

Html:

 <input type="text" class="inputFocus">

jQuery:

$(document).on("keypress",function(e){

    if(e.which==13 && !$(":focus").hasClass("inputFocus")) 
        $(".inputFocus").focus();

})

Final code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    
   <input type="text" class="inputFocus">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   <script>
    
    $(document).on("keypress",function(e){

        if(e.which==13 && !$(":focus").hasClass("inputFocus")) 
            $(".inputFocus").focus();

    })
    
       
    </script>
    </body>
</html>

Comments