views:

110

answers:

3

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 the textboxes are selected in 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?

+1  A: 

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.

meder
Thank you very much!
korvirlol
Sure, don't forget to check-mark if you find a correct solution :P
meder
A: 

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

Marek Karbarz
A: 

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.

Lucas Richter