views:

34

answers:

1

Hi

I need to get the first element from a form, could be a select, text, radio etc. I can get all the elements using the following:

$('myformcontainer').getElement('form').getElements('select,input[type=text]');

And this returns all my form elements, however the problem is that the items are organised by tag type (in this example; select items would be before any text field, even if the text field is first).

How can I sort this array so that the first item in the form is first? Or, a better way of getting them?

Btw, I've tried getFirst - it always returns null.

A: 

http://www.jsfiddle.net/EtGKE/

on markup of:

<form id="myform">
    <input type="text" value="bar" name="bar" />
    <select name="sel">
        <option>foo</option>
    </select>
    <input type="text" value="foo" name="foo" />
    <input type="password" />
</form>

with code:

var allEls = document.id('myform').getChildren().filter(function(el) {
    var tag = el.get("tag"), type = el.get("type");
    return tag == "select" || (tag == "input" && type == "text");
});

this will get you the natural order of the items as an array, use allElls[0] to reference the first one.

incidentally, this bug has been fixed in mootools 1.3 where the new slick selector engine will not break the order so your code will actually be working as expected.

Dimitar Christoff
"incidentally, this bug has been fixed in mootools 1.3" - For now, yes.
Oskar Krawczyk
Brilliant, thanks
Ashley