SkyeBoniwell
SkyeBoniwell

Reputation: 7122

looping through an array in jQuery

I'm trying to create an array of textarea values and then loop through them.

Here is a jsFiddle that I am trying to get this to work in:

http://jsfiddle.net/kxkHZ/1/

When I run it, nothing happens.

Any idea what I'm doing wrong?

var textArray = [];
$('[class=objectives]').each(function (i) {
     textArray.push($(this).val());
});

for (var i = 0; i < textArray.length; i++) {
     console.log(textArray[i].value);
}

Upvotes: 1

Views: 119

Answers (3)

Igor
Igor

Reputation: 34011

You are pushing the value of the element into the array, you do not need to call value on it again. Just access the string itself:

console.log(textArray[i]);

Upvotes: 4

Adil Shaikh
Adil Shaikh

Reputation: 44740

Working --> http://jsfiddle.net/kxkHZ/11/

for (var i = 0; i < textArray.length; i++) {
    // textArray[i] itself is the value so textArray[i].value is incorrect 
    console.log(textArray[i]); 
}

You forgot to include jquery -

You should have got an error $ is not defined.

Upvotes: 3

techfoobar
techfoobar

Reputation: 66693

There is no value property in each element, you can simply do:

for (var i = 0; i < textArray.length; i++) {
     console.log(textArray[i]);
}

Working Demo - Note: jQuery wasn't originally included

Upvotes: 5

Related Questions