1

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

4

4 回答 4

3

因为您在执行时遇到错误textArray.push(i.val());.. 中的第一个参数.each是索引,它是一个数字,应用.val会引发错误并跳出循环。

要么使用作为元素的第二个参数,要么使用this.

更改textArray.push(i.val());textArray.push($(this).val());

于 2013-04-26T13:56:05.050 回答
2

将循环更改为:

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

在您的代码中,i是一个索引 (0,1,2),尝试推入您的数组是没有意义的。.each()有两个参数,一个索引和一个值,而您试图使用索引的值,这当然不起作用。通过使用$(this).val(),您可以将 textarea 的值推送到您的数组中。

于 2013-04-26T13:55:26.533 回答
1

尝试像这样定义您的文本区域:

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

并使用:

$('textarea.objectives').each(function(i){
    //your code
})
于 2013-04-26T13:55:24.703 回答
1

您应该在控制台上遇到错误-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/

于 2013-04-26T13:55:53.787 回答