Javascript – How to select the first child form element (using prototype)

javascriptprototypejs

I want to set focus on the first form element in a div, either using something that Prototype gives me, or plain javascript. I have a reference to a div which contains the form elements. I don't know if the first form element will be an <input>, <select>, or <textarea> node.

I want to do something like this:

$('parentDiv').down('textarea, select, input').focus();

However, the Element.down method seems to pick the first textarea node, even though there is an input node before the textarea.

Is there an elegant way around this? I suppose I could get all the descendants of the parent div, and then iterate over each one looking for one of these nodes, but I suspect that there might be a cool way to do this in prototype.

I can't use the methods of the Form object, because this parent div is only part of the form. It is added to the page via an AJAX call, so when the div has been added to the DOM, I want to set focus on the first field in the newly added set (which is most likely not the first field in the whole form).

Thanks!

Best Answer

When I used prototype i'm sure I did something like this.

var firstElement = Form.findFirstElement(document.forms[0]);
if(firstElement !=null)
    firstElement.activate();

I would substitute your form for document.forms[0]

Prototype also has the method of focusFirstElement on the Form class, but I couldn't use that because some pages I would load didn't have forms. You might be able to just call Form.focusFirstElement($(form)); or a similar variation.

Edit:
I thought you could use the Form extensions on different types of elements but it doesn't appear to work, however you can take something from Form and apply it directly. The following code should work as you intend.

var firstElement = Form.getElements($("parentDiv")).find(function(element) {
    return element.type != 'hidden' && !element.disabled &&
    ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
if(firstElement != null)
    firstElement.activate();