tags:

views:

91

answers:

4

I'm interested in writing a very generic script that I can include into my masterpage that would give focus to the first textbox on the page, regardless of the page layout and contents. Would something like this work?

$(function() {
   $("input[type='text']:first").focus();
});

I'm worried that "first" is just whatever is the first textbox it finds using whatever indexing mechanism jquery uses internally rather than the first textbox (ie. top-most, left-most on the screen)

Thanks!

+1  A: 

From what I know, what you've written is pretty much correct. jQuery's selector :first uses the first element that it comes across in spanning the DOM tree. I believe there is no proprietary method here, just a simple tree traversal.

daveslab
+1  A: 

Your selector there is correct. jQuery's selector engine (Sizzle) uses CSS selectors, and the CSS :first psuedoselector will always choose the first in the document flow (i.e. the highest up in the source code).

slightlymore
Sounds to me like he wants position-based, not DOM-based traversal.
tvanfosson
+2  A: 

If you are using CSS to move things around on the page, then you'll probably need to search each and find the input that has the smallest, positive top/left position. If your inputs are in DOM order then you can use the method you've got in your question. The easiest way otherwise would be to tag the input you wanted with a class so that you could find it easily.

 <input type="text" id="rightBox" style="float: right;" />
 <input type="text" id="leftBox" class="chooseMe" />

 ...

 var firstText = $('input[type=text].chooseMe')[0];

 firstText.focus();
tvanfosson
+3  A: 

If you need to know based not on the tabindex / dom order, but based on CSS position, then you could try something like this:

var firstBox = null;
$("input[type='text']").each(function()
{
    if (firstBox == null) {
     firstBox = $(this);
    }
    else {
     if ($(this).offset().top < firstBox.offset().top || ($(this).offset().top == firstBox.offset().top && $(this).offset().left < firstBox.offset().left)) {
      firstBox = $(this);
     }
    }
});
aquinas