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

Recommended Answers

All 2 Replies

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;
}

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;
    });
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.