9

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,312
  • 7
  • 62
  • 87
GSto
  • 40,278
  • 37
  • 127
  • 179

3 Answers3

12

It might be this:

$("#newForm input:first").focus();
Fosco
  • 37,365
  • 6
  • 84
  • 100
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,265
  • 1
  • 15
  • 22
2

Try this:

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