views:

42

answers:

4

How to get the first form element (input element) that occurs on a page and set focus to it? I would like to change the practice where I have to set focus manually in every single page to a certain element like this

$("#Clients").focus()

I want something universal, something that will figure out the first input automatically and put that code into a master page.

+1  A: 
$(document).ready(function() {
    $('input').first().focus();
});
Litso
+3  A: 

You can use the :input and :first selectors with .focus(), like this:

$(function() {
  $(':input:first').focus();
});

Or since you said master page, you may have a certain content area or something, so just prefix that on the selector, for example:

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

The :input selectors selects all input, textarea, select and button elements, so it'll grab the first of any kind of <form> input.

Nick Craver
you rock, craver;)
mare
@mare - just trying to help :)
Nick Craver
A: 

This gives focus to the first textinput/textarea on the page

$(function(){
    $('input[type=text], textarea').first().focus();
})
Kristoffer S Hansen
+2  A: 

Here is a more foolproof way of doing it by selecting only the visible and enabled inputs.

$(function() {
  $(':input:visible:enabled:first').focus();
});
htanata
nice, thank you
mare