1

I am looking for a way to insert all the text from textareas to array and then convert it to string. I've tried this code:

(function () {
var array = [];
$('textarea').each(function () {
array.push(this.value);
});
});
string = array.toString()

but that returns [object Window]. Does anybody know how to fix this?

1
  • The issue with your code is that you're trying to access array outside of its scope (the anonymous function in which it is defined). Commented Aug 1, 2020 at 17:44

2 Answers 2

2

Basically you just closed the (function(){}); too early. Because you have defined the array variable inside the function it is not accessable outside. To fix it you could only close the (function(){}) a few lines further down. Do not forget to also run the function! See comments.

(function () {
    var array = [];
    
    $('textarea').each(function () {
        array.push(this.value);
    });

    var string = array.toString(); // add "var" in front of a new variable name
    console.log(string);

})(); // move this closing paranthesis further down and add () 
      // then it is an IIFE and will run
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea>111</textarea>
<textarea>222</textarea>
<textarea>333</textarea>

You could also do something like this (without jQuery and why use an array if you want a string)

var result = '';
[...document.querySelectorAll('textarea')].forEach(function(element){
    result = result + element.innerHTML;
});

console.log(result);
<textarea>111</textarea>
<textarea>222</textarea>
<textarea>333</textarea>

or if you want to do the push to array convert back to string you can use .join() (jQuery is not needed)

var result = [];
[...document.querySelectorAll('textarea')].forEach(function(element){
    result.push(element.innerHTML);
});

console.log(result.join());
<textarea>111</textarea>
<textarea>222</textarea>
<textarea>333</textarea>

Sign up to request clarification or add additional context in comments.

Comments

1

If you need a function to apply, you can do it without jQuery:

function getTextAreasString() {
    var textArray = []
    Array.from(document.getElementsByTagName("textarea")).forEach(
        textarea => textArray.push(textarea.textContent)
    )
    return textArray;
}

The idea is to get all textarea elements, add them to an array, and return that array with all the textContent of tags you processed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.