GSto
GSto

Reputation: 42380

Move focus to a particular field

I have a button that will add show a form on the page. how can I move the focus to the first field of the form when that button is clicked?

simple example:

HTML:

<form style="display:none;" id="newForm">
   <input type="text" id="firstField">
</form>
<input type="button" id="showForm" value="add new">

jQuery:

 $("#showForm").click(function(){
     $("#newForm").show();
     //move focus??
});

Upvotes: 11

Views: 7361

Answers (3)

Paul Dragoonis
Paul Dragoonis

Reputation: 2333

A quicker lookup would simply be.

$('#firstField').focus()

However if you removed the ID from your element then this would be better but slightly slower.

$('#newForm input:first').focus();

Upvotes: 8

Rakward
Rakward

Reputation: 1717

Try this:

$('input#firstfield').focus();

Upvotes: 3

Fosco
Fosco

Reputation: 38526

It might be this:

$("#newForm input:first").focus();

Upvotes: 14

Related Questions