107

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?

yPhil
  • 8,049
  • 4
  • 57
  • 83
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212
  • 2
    I'm not 100% sure (hence the comment) but it may involve splitting the text at every "\n" – Pluckerpluck Feb 08 '12 at 16:05
  • 1
    possible duplicate of [parse a textarea in substrings based on line breaks in Javascript](http://stackoverflow.com/questions/3800795/parse-a-textarea-in-substrings-based-on-line-breaks-in-javascript) – Michael Berkowski Feb 08 '12 at 16:06

6 Answers6

198

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
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 20
    Instead of using `$('textarea').val()` use `document.getElementById('textareaId').innerHTML` thats it. – ShankarSangoli Feb 08 '12 at 16:13
  • 3
    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 new – SoWhat Feb 08 '12 at 16:52
  • 1
    Yes you can even access it using document.formname.textareName.value – ShankarSangoli Feb 08 '12 at 17:46
  • 4
    Are lines guaranteed to end in \n and not \r\n ? – Oztaco Jun 07 '18 at 20:55
  • 2
    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 tags, but this not modified when a user adds input. – Eric Barker May 01 '20 at 14:13
  • @Oztaco-ReinstateMonicaC. The WHATWG's HTML [Living Standard](https://html.spec.whatwg.org/multipage/form-elements.html#htmltextareaelement) 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. – user98761 Aug 25 '20 at 22:28
  • @EricBarker did you mean `document.getElementsByTagName` as `textarea` is a tag name. – SimpleGuy Dec 15 '20 at 12:15
  • using regex `.split(/^.*$/gm)` – Hanna Rose Aug 20 '21 at 20:03
44

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
kojow7
  • 10,308
  • 17
  • 80
  • 135
Paweł Brewczynski
  • 2,665
  • 3
  • 30
  • 43
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)
})
whitneyland
  • 10,632
  • 9
  • 60
  • 68
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));
}
Joe
  • 15,669
  • 4
  • 48
  • 83
  • 4
    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... – IMSoP Nov 25 '12 at 13:44
4

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
sinsedrix
  • 4,336
  • 4
  • 29
  • 53
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>