views:

147

answers:

2

I have a requirement in Javascript (using Prototype) to focus the cursor on the first form item within a specific div.

Simple example:

<form id="theForm">
  <div id="part1">
    <input id="aaa" .../>
    <select id="bbb">...</select>
  </div>
  <div id="part2">
    <select id="ccc">...</select>
    <input id="ddd" .../>
  </div>
</form>

I want to write a Javascript function that takes the name of a div within theForm and focuses the cursor on the first item in that div - e.g.

focusOnFirst('part1'); // will put focus on input "aaa"
focusOnFirst('part2'); // will put focus on select "ccc"

I thought I might be able to use Prototype's select method like this:

$(pDiv).select('input','select',...etc.);

However, this returns an array that contains all the inputs, followed by all the selects, etc. It doesn't return the items in the order they appear within the div. In my example above, this results in putting focus on the input "ddd" rather than the select "ccc".

Another possibility is the Form getElements method:

$('theForm').getElements();

But now I need to interrogate each item returned to see if it falls inside the required div. And currently the only way I know to do that is to get all its ancestors and see if any is the selected div. I could do that, but I fear it won't be the most efficient solution.

Can anyone suggest a better way?

+1  A: 

What about using a CSS3 selector:

$$('#theForm input:first-of-type')[0].focus()

It returns an array, even if we know it's only going to contain one element, so just grab the first one and focus it.

I've worked up a quick example.

--Edit OK, I just realised it misses the select element.

--Edit This seems to work - select the first element with a name attribute (assuming you've got name attributes, could use something else):

function focusOnFirst2(divName) {
    $$('#' + divName + ' [name]')[0].focus();
}

I've updated my linked example to include this as well as my erroneous first attempt.

--Edit One last time :)

I've taken your function and attempted to turn it around so it searches based on the children of the div rather than the children of the form. I stuck it in a loop to call it 100 times and see ~45% improvement in IE, whether it'll be any better for you in the real world I'm not sure:

function focusFirstItem (divId)
{
    if ($(divId))
    {
        var elems = $('myForm').getElements();
        var elems2 = $(divId).select('*');
        for (i=0, l=elems2.length; i<l; ++i) {
            var item = elems2[i];
            if (item.id && !item.disabled && !item.readOnly && item.visible) {
                if (elems.find(function(s){return s.id = item.id}))
                item.focus();
                break;
            }
        }
    }
}

In example page with rudimentary timing.

robertc
Thanks, especially for adding an example. However, I still hit the same problem with this when the items can be inputs or selects (or textareas etc.): depending on the order in which you specify them you get different results. If you change your item "Three" to a select list and change the code to "$$('#' + divName + ' input:first-of-type', '#' + divName + ' select:first-of-type')[0].focus()" then the Div Two button puts focus on item "Four" instead of "Three", unless you swap the 2 parameters. This despite the Prototype docs saying "returns a document-order array of extended DOM elements"
Tony Andrews
Yeah, I just realised that - wasn't thinking about select elements at all.
robertc
You don't have name attributes in your code above, I suppose if you have to add attributes you may as well add a class name and select on that.
robertc
I do have names and classes in my real code, that was just a quick and dirty example! Unfortunately I'm trying to write some generic code that will work on many existing pages, so I don't want to have to modify the existing HTML.
Tony Andrews
Fair enough - I went with the name attribute because all my form elements have one, can't recall exactly but I think it was because IE6 didn't identify the elements when POSTing unless there was a name.
robertc
Thanks, Robert, reading this at home now, will try your suggestions in the morning.
Tony Andrews
Actually, tomorrow (Thursday) or later, since heavy snow has prevented me getting in to work today.
Tony Andrews
I'm at home too - didn't want to risk the London transport when it's going to carry on snowing all day :)
robertc
Right, had a chance to try it now. It performs better than mine, 530ms instead of 670ms on IE6 for my test case, so I've adopted it - thanks.
Tony Andrews
+1  A: 

This is what I have managed to come up with so far:

focusFirstItem (divId)
{
    if ($(divId))
    {
        var elems = $('myForm').getElements();
        for (i=0, l=elems.length; i<l; ++i) {
            var item = $(elems[i]);
            if (!item.disabled && !item.readOnly && item.visible) {
                if (item.ancestors().find(function(s){return s.id == divId})) {
                    $(item).focus();
                    break;
                }
            }
        }
    }
}

Horrible, I know. It takes about half a second to run on IE6, a much better 70ms or so on FF. I know I should be able to get rid of the "for" loop using Prototype, but I dismally failed in my attempts to do so.

Tony Andrews
I think the .ancestors call might be good target for optimisation - it's going to be collecting a lot of the same elements every time through the loop? Can you time how long the $('myForm').getElements() takes by itself?
robertc
I tried turning your approach slightly sideways, added to my answer.
robertc