1

I am having 2 divs:

<div id="player" class="setPlayers">value1</div>
<div id="player2" class="setPlayers">value2</div>

All I want to do is to set the value1 and value2 of the divs to an array for reading later on; I tried out this code, but doesn' t work:

var array = new Array();

$.each($('.setPlayers'), function(key, object) {
    console.log(index + ':' + value);
    array.push(value);
    alert(value);
});

$.each(array, function(index, value) {
    console.log(index + ':' + value);
    console.log(index + ':' + $(this).val());
});​

what' s wrong according to you ?,cheers

1
  • Well just as a code review level, where does the variable "value" get declared, in the first each ? Commented Aug 22, 2012 at 11:49

4 Answers 4

5

Using your code as a start I came up with:

$(function(){
  var array = [];

  $('.setPlayers').each(function(index) {
      console.log(index + ':' + $(this).text());
      array.push($(this).text());
      alert($(this).text());
  });

  $.each(array, function(index) {
      console.log(index + ':' + this);
      console.log(index + ':' + this);
  });
});

Few too many alerts and debug for my liking.

If you just want to fill the array then this will do:

$(function(){
  var array = $('.setPlayers').map(function() { return $(this).text()); }).get();
});
​
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers Gerbil, that, exactly what I need, yes indeed many alerts :)
3

Try this (see demo: http://jsfiddle.net/GcjgH/):

var array = $('.setPlayers').map(function() {
  return $(this).text();
}).get();

alert(array[0]);
alert(array[1]);
​

Comments

0

The correct syntax would be $('.setPlayers').each(function(){ ... });

In the context of the question:

$('.setPlayers').each(function(){
     console.log($(this).attr("id")+':'+$(this).text());
     array.push($(this).text());
     alert($(this).text());
});

for (var i=0; i<array.len; i++){
    console.log(arr[i]);
}

etc.

Comments

0

This should work:

var array = new Array();
$(".setPlayers").each(function() {
    array.push($(this).text());
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.