korvirlol
korvirlol

Reputation: 19

jquery .each iteration

If you have more than 1 (dynamic) text boxes with the same class name and use jquery to loop through each of said text boxes, can you assume that the order in which the textboxes are selected is the same every time?

Example:

Text box 1 value = 1 text box 2 value = 2 text box 3 value = 3

$(".textboxes").each(function(){
     alert( $(this).val() );
});

Will it always print these values in the same order every time?

Upvotes: 1

Views: 2918

Answers (3)

Lucas Wilson-Richter
Lucas Wilson-Richter

Reputation: 2324

Should it matter? If you're writing a .each function, you should be doing the same thing to every element. Otherwise you should use some other method. Hence, the order in which the elements appear probably shouldn't matter, and if it does, you may have discovered a code smell.

If you're looking for a way to individually identify each of the elements in the list, you could try using its ID, e.g:

alert($(this).id + ": " + $(this).val);

This has the advantage that if an expected element doesn't appear in your list, it's a little easier to identify.

Upvotes: -3

Marek Karbarz
Marek Karbarz

Reputation: 29324

jQuery will get the elements from top to bottom and always in the same way, so the order will be the same every time

Upvotes: 1

meder omuraliev
meder omuraliev

Reputation: 186762

The loop starts from the beginning to the end, 0 to the max .length if > 0, so it will always go in the same order if you provide an html selector ( which would pick up elements in the order they are defined in the structure/markup ).

However if you fed an object to $.each directly, since there is no standard way or rule dictating how the ordering should be, usually it would go in the order they're defined for most interpreters I've seen, but interpreters aren't really supposed to obey this "rule".

each: function( object, callback, args ) {
    var name, i = 0, length = object.length;

    if ( args ) {
        if ( length === undefined ) {
            for ( name in object )
                if ( callback.apply( object[ name ], args ) === false )
                    break;
        } else
            for ( ; i < length; )
                if ( callback.apply( object[ i++ ], args ) === false )
                    break;

As you can see the second for loop is the one that's actually executed.

Upvotes: 8

Related Questions