SkyeBoniwell
SkyeBoniwell

Reputation: 7122

jquery array not looping through all elements

I am creating an array of text values from a group of dynamically generated textareas.

I put an alert statement in the loop to see if it was working, and it's only alerting the first textarea that it encounters but none of the rest.

Here is my jQuery:

var textArray = [];

$('[name=txtObjective]').each(function (i) {
     alert($(this).val());
     textArray.push(i.val());
});

And here is what my textareas look like:

 <textarea name='txtObjective' class='objectives'>this is some text</textarea>
 <textarea name='txtObjective' class='objectives'>this is some more text</textarea>
 <textarea name='txtObjective' class='objectives'>this is even some more text</textarea>

Any clue what I'm doing wrong?

Thanks

Upvotes: 1

Views: 82

Answers (4)

j08691
j08691

Reputation: 208032

Change your loop to:

$('[name=txtObjective]').each(function (i) {
     textArray.push($(this).val());
});

In your code, i is an index (0,1,2) which makes no sense to try and push into your array. .each() has two parameters, an index and a value, and you were trying to use the value of the index which of course doesn't work. By using $(this).val() you can push the value of the textarea into your array.

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

Because you are getting an error when executing textArray.push(i.val());.. The first arg in .each is index which is an number and applying .val would throw an error and breaks out of the loop.

Either use the second arg which is the element or use this.

Change textArray.push(i.val()); to textArray.push($(this).val());

Upvotes: 3

Adil Shaikh
Adil Shaikh

Reputation: 44740

You should have got error on console - Object 0 has no method 'val'

$('[name=txtObjective]').each(function (i) {
     alert($(this).val());
     textArray.push($(this).val()); // <<-- use $(this) here instead of i
});

http://jsfiddle.net/mohammadAdil/j8JgX/

Upvotes: 1

Brewal
Brewal

Reputation: 8199

Try defining your textareas like so :

<textarea name='txtObjective[]' class='objectives'>

And use :

$('textarea.objectives').each(function(i){
    //your code
})

Upvotes: 1

Related Questions