10

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??
});
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
GSto
  • 41,512
  • 37
  • 133
  • 184

3 Answers3

13

It might be this:

$("#newForm input:first").focus();
Fosco
  • 38,138
  • 7
  • 87
  • 101
7

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();
Paul Dragoonis
  • 2,315
  • 1
  • 16
  • 22
2

Try this:

$('input#firstfield').focus();
Rakward
  • 1,657
  • 2
  • 18
  • 24