Darkalfx
Darkalfx

Reputation: 259

How to put focus on a textbox?

How do I put focus on a textbox with JavaScript(Or jQuery)?

I have a textbox on a page and after the user presses the enter key, the textbox loses focus. (Keep in mind that no post occurs, the page does not refresh)

I want to be able set the focus back inside of the textbox through javascript so that the user can continue typing and doesn't have to click on anything.

I tried adding the following code after the users has pressed the enter key:

$(".focus").focus();

The code for my textbox:

<input type="text" class="focus" />

but alas, the cursor does not appear inside of the textbox and the user still has to click to continue typing.

How do I fix this problem?

Upvotes: 2

Views: 1384

Answers (2)

JKirchartz
JKirchartz

Reputation: 18022

You have to apply the focus code to the input, if the page hasn't loaded or the DOM isn't ready when the code runs, then there's no input yet to focus on..

So you have to check that the DOM is loaded, like this:

$(function(){
    $(".focus").focus();
});

http://jsfiddle.net/c7aUS/

You can also include the code at the bottom of the page, before the </body> tag, so that it loads right after all your HTML.

note: If you're running this in jsfiddle, by default your code is run on page load. When using JQuery, it automatically wraps it in this code:

$(window).load(function(){
     //your code here
});

EDIT:

In that case, meetamit is very helpful, I think you're looking for this:

$(function(){
    $(".focus").focus();
    $(".focus").on('keydown', function(event) {
        if(event.which == 13) {// Enter key pressed
            $this = $(this);
            $this.focus();
            var value = $this.val();
            $this.val(''); /* clear the field */
            // do stuff with the value
        }
    });
});​

http://jsfiddle.net/c7aUS/1/

Upvotes: 2

meetamit
meetamit

Reputation: 25157

Why does pressing the enter key take away the focus from the field? (I couldn't reproduce it.) It might suggest that there's a hidden problem still. Maybe not. If not, this might help:

$(".focus").on('keydown', function(event) {
    if(event.which == 13) {// Enter key pressed
        event.preventDefault();
    }
});

Upvotes: 1

Related Questions