How to read line by line of a text area HTML tag
Asked Answered
Z

6

108

I have a text area where each line contains Integer value like follows

      1234
      4321
     123445

I want to check if the user has really enetered valid values and not some funny values like follows

      1234,
      987l;

For that I need to read line by line of text area and validate that. How can i read line by line of a text area using javascript?

Zenas answered 8/2, 2012 at 16:4 Comment(2)
I'm not 100% sure (hence the comment) but it may involve splitting the text at every "\n"Ingathering
possible duplicate of parse a textarea in substrings based on line breaks in JavascriptKiaochow
B
200

Try this.

var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
    //code here using lines[i] which will give you each line
}
Blip answered 8/2, 2012 at 16:6 Comment(8)
Instead of using $('textarea').val() use document.getElementById('textareaId').innerHTML thats it.Blip
i remember there was another method we used. We used form.elementname or something. I mean long time back. 6-7 years ago when DOM was quite newFrequent
Yes you can even access it using document.formname.textareName.valueBlip
Are lines guaranteed to end in \n and not \r\n ?Fourier
For those who are here in 2020, I can't say for sure what the browser behavior was when the above comments were added but currently Chrome does not recognize document.getElementById('textarea').innerHTML UNLESS it is already loaded as placeholder text in the original load of the DOM. You would need to use document.getElementById('textarea').value to access any text the user has entered or modified. On page load, placeholder text is put as inner HTML between the <textarea></textarea> tags, but this not modified when a user adds input.Toscanini
@Oztaco-ReinstateMonicaC. The WHATWG's HTML Living Standard says: "The algorithm for obtaining the element's API value is to return the element's raw value, with newlines normalized." The linked explanation for "newlines normalized" says: "To normalize newlines in a string, replace every U+000D CR U+000A LF code point pair with a single U+000A LF code point, and then replace every remaining U+000D CR code point with a U+000A LF code point." So, yes, it's guaranteed in conforming implementations.Revivalist
@EricBarker did you mean document.getElementsByTagName as textarea is a tag name.Arbitration
using regex .split(/^.*$/gm)Misology
S
45

This works without needing jQuery:

var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
Supersedure answered 30/6, 2013 at 16:46 Comment(0)
C
6

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)
})
Cuddle answered 23/9, 2017 at 23:3 Comment(0)
S
5

This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.

var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
    if (parseInt($(this) != 'NaN')
        lines[] = parseInt($(this));
}
Septima answered 8/2, 2012 at 16:9 Comment(1)
As a general note, you nearly always want to pass the second argument to parseInt to force reading as base 10 / decimal (parseInt(this, 10)). Otherwise, leading zeroes lead to interpretation as base 8 (octal), which can lead to some rather odd behaviour...Alber
A
4

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
Ahl answered 8/2, 2012 at 16:7 Comment(0)
T
0

A simplifyied Function could be like this:

function fetch (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}

for the html code below (as an example only):

<textarea  id="targetted_textarea" rows="6" cols="60">
  At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
  </textarea>
  <button onclick="fetch('targetted_textarea','destination')" id="convert">Convert</button>

<div id="destination">Had not been fetched yet click convert to fetch ..!</div>
To answered 20/4, 2022 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.