2

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?

2
  • 2
    How exactly did you add the focus() code after the user pressed Enter? Commented Nov 5, 2012 at 3:39
  • I've updated my answer, I hope it helps. Commented Nov 6, 2012 at 4:15

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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(); } }); 

2 Comments

This is a solution, although not very elegant IMO. The enter key may be needed for something else later. preventDefault() on something as necessary as the enter key should be the absolute last resort. Maybe not even that.
@Abhilash This only prevents default IN the specified field, everywhere else it works as expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.