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?
What about using a CSS3 selector:
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
nameattribute (assuming you’ve got name attributes, could use something else):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:
In example page with rudimentary timing.