Reputation: 585
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);
});
Upvotes: 0
Views: 657
Reputation: 9876
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);
});
Upvotes: 4
Reputation: 324780
Ignore everything else, just focus on the line that's apparently the problem:
var pName = $('input.player').val();
What does this line do? It gives you the value of the first 'input.player'
element (see documentation).
And, funnily enough, this is exactly the result you see: the value of the first input over and over again.
Your code is doing exactly what you told it to do, but that is not what you meant.
Within a .each
loop, the keyword this
refers to the current element in the loop. Since it's a raw DOM node and not a jQuery object, you will need to wrap it as $(this)
... but since you are only getting its value, the Vanilla JS version this.value
will work far more efficiently.
See Nick Bull's answer for actual code, I just wanted to outline how to approach debugging code yourself.
Upvotes: 2