0
function name_loop(){
    var names_array = [];
    $('.name_class').each(function(index){
        names_array[index] = $.trim($(this).val());
    });
    return names_array;
}

the problem with the above code is that it returns only the first element and not the specified array. can someone solve it for me

Edited by pritaeas: Wrong forum.

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by JJenZz
0

Hi,
In your code, the "index" remains the same, but it should be incremented.
Try this:

function name_loop(){
  var names_array = [];
  var index = 0;
  $('.name_class').each(function(){
     names_array[index] = $.trim($(this).val());
     index++;
  });
  return names_array;
}
0

MarPio is incorrect. Your index does not remain the same because the .each() method in jQuery (which it looks like you're using) passes the incremented index as a parameter to the callback which you seem to be well aware of by looking at your code.

There is in fact nothing wrong with your code (it does what you expect). You can see it working fine here: http://jsfiddle.net/cYmr9/

I'd suggest changing $(this).val() to this.value though because there's an unecessary performance impact by creating a new jQuery object ($(this)) in each iteration of that loop.

Or.... you could simplify it even further and just do this (which will produce the same result):

function name_loop(){
    return $('.name_class').map(function() {
        return this.value;
    });
}

Edited by JJenZz

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.