TopTomato TopTomato - 3 months ago 17
jQuery Question

jQuery's $.each function repeatedly adding val of first item only

I’m trying to use jQuery’s Each function to iterate over 3 text inputs and put each one’s value into an array. My code below is not working. Instead it is adding the value of the first input only and doing so 3 times. So the resulting array is:
players = [‘Bob’, ‘Bob’, ‘Bob’]

instead of:
players = [‘Bob’, ‘Tom’, ‘Ziggy’];

I know it has something to do w the index not being applied per input item but don’t know how to remedy this.

The markup is this:

<input type="text" class="player" id="player1" value="Bob" /><br>
<input type="text" class="player" id="player2" value="Tom" /><br>
<input type="text" class="player" id="player3" value="Ziggy" /><br>
<input type="submit" id="submit" value="submit" />


Js is this:

var players = [];

$('#submit').click(function(){
$.each($('input.player'), function(index){
var pName = $('input.player').val();
//var pName = index.val(); tried this too
players.push(pName);
console.log(index);
console.log(players);

});

Answer

Within .each(), you need to use $(this) to access the current element:

var players = [];

$('#submit').click(function(){
  $.each($('input.player'), function(index){
    var pName = $(this).val();
    players.push(pName);
    console.log(index);
    console.log(players);
  });
});

Note that this is equivalent to your .each() function, and IMO easier to read:

$('input.player').each(function(index){
    var pName = $(this).val();
    players.push(pName);
    console.log(index);
    console.log(players);
});

According to Ozan:

You could also use the second parameter of the callback function of $.each()

And the jQuery docs agree:

Type: Function( Integer index, Element element )

$('input.player').each(function(index, element){
    var pName = $(element).val(); // Note the changed line here
    players.push(pName);
    console.log(index);
    console.log(players);
});