Store multiple textareas in different array's index

Viewed 133

I have multiple textarea for example:

<textarea>test1</textarea>
<textarea>test2</textarea>
<textarea>test3</textarea>

I know how to iterate over all the textareas and get the values:

$(function(){
    $("textarea").each(function(){
      alert(this.value);
    });
});

But how to store each textarea at a different index?

This doesn't work:

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

Doesn't matter if it's with JS or Jquery

3 Answers

I believe you are trying to log the array before the loop is executed:

var myArray=[];     
$(function(){
  $("textarea").each(function(){
    myArray.push(this.value);
  });
  console.log('----after the loop execution-----');
  console.log(myArray); //["test1", "test2", "test3"]
});
console.log('----before the loop execution-----');
console.log(myArray); //[]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea>test1</textarea>
<textarea>test2</textarea>
<textarea>test3</textarea>

    let answer = []
    let texts = document.querySelectorAll('textarea')
    texts.forEach( x => answer.push(x.value))
    console.log(answer)
<textarea>test1</textarea>
<textarea>test22</textarea>
<textarea>test333</textarea>

Native code, you can make it without 'this'

You must console your array myArray inside function scope after iteration like this:

var myArray=[];     
$(function(){
 $("textarea").each(function(){
  myArray.push(this.value);
 });
 console.log(myArray);
});
Related