2

I have 3 textarea elements on my page and there could be more than 3 in the future.

I want to get all the text from these textarea fields.

If I do $('textarea').val(); in chrome console, it only returns the first textarea's text.

How do I get the texts of all the elements in an array?

2 Answers 2

3

jQuery getters only return value of the first matched element, you should iterate through the collection, you can use .map() method which iterates through the collection behind the scene and returns a jQuery-wrapped array, by calling .get() method you can get the actual array.

var arr = $('textarea').map(function() {
     return $.trim(this.value);
}).get();

As Pointy correctly mentions, for converting an array to a string you can use .join() method.

var str = arr.join(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Yes. That'll get you an array of all the values. If you want a combined string, you can just .join() that result.
Note how $('textarea') is an object containing all textarea elements in the DOM, but applying the .val() method directly to it only returns the value of the first element in the object. This is why you need to iterate over all the elements in the object, as can be done with the .map() or .each() methods.
I tried your answer without the get() at the end and it seems to return the same array as with it, what it the get() for?
@sonnyhe2002 Now it's a jQuery-wrapped array, you can call all jQuery methods on it.
3
(function () {
    var arr = [];
    $('textarea').each(function () {
        arr.push(this.value);
    });
} ());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.