0

I'm trying to get the value of the first and second line from a textarea in HTML.

The main problem is that the first and second line can be of different lengths, so I can't just copy X amount of characters.

Most of the solutions I've seen include JQuery, which I'm not familiar with, so I would prefer an answer that doesn't involve JQuery. However, if you do have an answer that does use JQuery, I'll also give it a go. Here's my code so far:

textarea {
  resize: none;
}
<textarea id="c" placeholder="c" spellcheck="false"></textarea>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • If you have `123456789012345678901234567` as one long piece of text and `123456789012345678901234567` wraps onto a new line (with the first containing `1234567890123456789012` and the next line containing `34567`) would this line of text be considered two lines in your case, or does a new line need to be separated by the user hitting "enter". – Nick Parsons Sep 12 '20 at 06:16
  • Look here: https://stackoverflow.com/questions/9196954/how-to-read-line-by-line-of-a-text-area-html-tag – AbsoluteBeginner Sep 12 '20 at 07:04
  • @NickParsons The line needs to be seperated by hitting enter. I then also want to get the value of that line as its own variable. If you have a solution that might work that would be much appreciated. –  Sep 12 '20 at 08:22

2 Answers2

0

Assuming that the first and second line are separated by a newline (by pressing enter), you split it by "\n" then get the second element.

function getSecondLine() {
    var tarea = document.getElementById("c")
    var tareavalue = tarea.value;
    var secondLine = tareavalue.split("\n")[1];
    console.log(secondLine)
}
0

function getfirstAndsecondLine(inp) {
var splittedInput = document.getElementById(inp).value.split('\n');
var firstLine = splittedInput[0];
var secondLine = splittedInput[1];
console.log('first Line :' + firstLine);
console.log(" ");
console.log('second Line :' + secondLine);
}
<textarea id="c" placeholder="c" spellcheck="false"></textarea>
<button onclick=getfirstAndsecondLine('c')>
get first and second line
</button>
sandeep joshi
  • 1,991
  • 1
  • 8
  • 13