如何将textarea内容推送到数组中

时间:2016-05-29 19:52:38

标签: javascript textarea

我有一个用户可以写入的textarea。是否可以将其推入数组?当我在console.log中时,我得到了#34; [object HTMLTextAreaElement]" - 这是可以做到的吗?

<textarea id="sermon" cols="100" rows="20">
Write here...
</textarea>

</div> <button id="newContent"><a href='#' onclick='downloadCSV({ filename: "card-data.csv" });'>Download your text to a CSV.</a></button>


var myArray = [];
myArray.push(sermon);
console.log(myArray.join());

3 个答案:

答案 0 :(得分:0)

尝试使用toString()函数,如下所示:

Write here...
</textarea>

</div> <button id="newContent"><a href='#' onclick='downloadCSV({ filename: "card-data.csv" });'>Download your text to a CSV.</a></button>


var myArray = [];
myArray.push(sermon.toString());
console.log(myArray.join());

答案 1 :(得分:0)

HTML应该是这样的:

<textarea id="sermon" cols="100" rows="20">

</textarea>

<button onclick="pushData()">Add to Array</button>

Javascript应该是这样的:

function pushData(){
   var text= document.getElementById("sermon").value;

    var array = [];

    array.push(text); 

    console.log(array.toString());
}

答案 2 :(得分:0)

您可能会觉得不方便调用内联javascript,但将某些操作绑定到click事件。

Html

<textarea id="sermon" cols="100" rows="20">
Write here...
</textarea>

<button id="newContent">Download your text to a CSV.</button>

的Javascript

// wait for your page to be loaded
window.onload = function() {
  // declare your empty variables
  var myArray = [];
  var sermon;

  // find the button element
  var button = document.getElementById('newContent');

  // attach some code to execute on click event
  button.onclick = function() {
    // put a call to your download function here

    // get the new value of the text area
    sermon = document.getElementById('sermon').value;

    myArray.push(sermon);
    console.log(myArray.join());
}  
};