faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

42 of 184 people (23%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Can I read and write the lines of a text area?

Mar 23rd, 2000 11:28
Martin Honnen,


There is no predefined api breaking the textareas value into lines, it 
is just one long string you need to apply string functions to. The 
following is an example on how to do it (using JavaScript 1.2):

<HTML>
<HEAD>
<STYLE>

</STYLE>
<SCRIPT>
function setTALine (textArea, lineNo, text) {
  var lines = textArea.value.split(/\r\n|\r|\n/);
  if (lineNo >= 0 && lines.length > lineNo)
    lines[lineNo] = text;
  textArea.value = lines.join('\n');
} 
function getTALine(textArea, lineNo) {
  var lines = textArea.value.split(/\r\n|\r|\n/);
  if (lineNo >= 0 && lines.length > lineNo)
    return lines[lineNo]
  else 
    return null;
}
var n = 20;
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName">
<SELECT NAME="lineNo">
<SCRIPT>
for (var i = 0; i < n; i++)
  document.write('<OPTION>' + i);
</SCRIPT>
</SELECT>
<INPUT TYPE="text" NAME="line" SIZE="80">
<BR>
<INPUT TYPE="button" VALUE="get line"
       ONCLICK="var lineNo = this.form.lineNo.selectedIndex;
                this.form.line.value = getTALine(this.form.textarea1, 
lineNo);
               "
>
<INPUT TYPE="button" VALUE="set line"
       ONCLICK="var lineNo = this.form.lineNo.selectedIndex;
                setTALine(this.form.textarea1, lineNo, 
this.form.line.value);
               "
>
<BR>
<SCRIPT>
document.write('<TEXTAREA NAME="textarea1" ROWS="5" COLS="20">');
for (var i = 0; i < n; i++)
  document.writeln(i + ': Kibology for all.');
document.write('<\/TEXTAREA>');
</SCRIPT>
</FORM>
</BODY>
</HTML>