yawnmoth wrote:
Say I have two input elements and that I wanted to make it so that when
the first ones input was what it should be, the focus would
automatically be shifted to the next input element.
ie. something like...
<input onkeyup="if (this.value.length == this.maxlength)
document.forms[0].elements['part2'].focus()" value="whatever"
maxvalue="x" type="text" />
<input value="whatever" maxvalue="x" type="text" />
This, unfortunately, doesn't work for me because, in my case, I have no
way of knowing what the id attribute is going to be. So is there a way
I can change the focus to the next element, whatever that element is?
You can either go to the next element in the DOM tree (which would be
very unreliable), the next element in the form's elements collection
(if there is a next element) or you could use the tabIndex property.
The following script uses the 'next form element' method, but you could
get the element's tabIndex property and find the element with the next
tab index if you think the 'next' element isn't the next in the form's
elements collection.
<script type="text/javascript">
function doNext(el)
{
if (el.value.length < el.getAttribute('maxlength')) return;
var f = el.form;
var els = f.elements;
var x, nextEl;
for (var i=0, len=els.length; i<len; i++){
x = els[i];
if (el == x && (nextEl = els[i+1])){
if (nextEl.focus) nextEl.focus();
}
}
}
</script>
<form action="">
<table>
<tr>
<td>
<input type="text" maxlength="5" value="1234"
onkeyup="doNext(this);">
</td>
<td>
<input type="text">
</td>
</tr>
</table>
</form>
You might be able to get the tabIndex property, then just set focus on
the tabIndex+1 element of the elements collection, but that might be
unreliable, you should test it thoroughly (it works in Firefox 1.5 & IE
6 at least):
function doNext(el)
{
if (el.value.length < el.getAttribute('maxlength')) return;
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
--
Rob