How would I populate an array from text in a <textarea> input?
My end goal is to take a list of names and then insert it into an array to perform some operations. The names would be separated by lines, like this:
bob
tim
sally
and then added to the array. To be honest, I don't know where to start other than adding the <textarea> and creating a blank array. I was reading other posts, but they were in jQuery or some other language that I don't know yet. My understanding is that I have to split the content somehow?
It's pretty straightforward:
var textarea = document.querySelector('textarea#names');
var textareaValue = textarea.value; // 'bob\ntim\nsally';
var arr = textareValue.split('\n');
split() takes string and cuts it into an array every given character (or string).
\n is new line character.
Edit: Answer to questions asked in comment below:
var names = [];
var textarea = document.querySelector('textarea#names');
function saveNames() {
names = textarea.value.split('\n');
}
textarea.addEventListener('blur', saveNames, false);
// or this:
// textarea.addEventListener('keyup', saveNames, false);
You use events. You can use blur event or even keyup event. Basically you listen for (events) something to happen (like textarea loose focus or user press keyboard button), and then do something (read textarea value and save names to array).
This is of course pure js, but if you want to use jquery, then you need to go to jquery reference and see how to use events with jquery.
Let's assume you have a textarea and after typing each name you hit return. This should get you started:
<textarea id="textToArray" style="width:300px; height:120px;"></textarea>
<button onclick="toArray()">To Array</button>
<div id="arrayOutput"><div/>
<script type="text/javascript">
function toArray( ) {
var textAreaElement = document.getElementById('textToArray');
var namesArray = textAreaElement.value.trim().split('\n');
console.log( namesArray );
document.getElementById('arrayOutput').innerText = JSON.stringify(namesArray);
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With