Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??
});
like image 330
GSto Avatar asked Jul 30 '10 19:07

GSto


3 Answers

It might be this:

$("#newForm input:first").focus();
like image 149
Fosco Avatar answered Nov 18 '22 05:11

Fosco


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();
like image 7
Paul Dragoonis Avatar answered Nov 18 '22 07:11

Paul Dragoonis


Try this:

$('input#firstfield').focus();
like image 2
Rakward Avatar answered Nov 18 '22 07:11

Rakward