21

I have a code where it saves multiple textarea values in a text file. However, it does not display the line breaks I indicated after saving it. It only identifies the line breaks w/c are manually put within the textarea. Below is the code. Please help.

<script>
    var TestVar = new Array(); 
    var i = 0;
    function save()
    {
        TestVar[i] = document.getElementById("text1").value + "\n" + document.getElementById("text2").value;
        mydoc = document.open();
        mydoc.write(TestVar);
        mydoc.execCommand("saveAs",true,"TicketID.txt");
        mydoc.close();
    }
</script>
</head>
<body>
    <form id=formtest>
        <textarea name="textarea" id="text1"></textarea>
        <textarea name="textarea" id="text2"></textarea>
        <input type="button" value="save" onclick="save()">
    </form>
</body>

Alex M
  • 371
  • 1
  • 3
  • 13
  • what is your server side code that saves this data? – MaVRoSCy Oct 15 '12 at 13:23
  • 1
    if you are on PHP, you should consider using "nl2br" PHP function when saving your textbox's data in the table. you can later convert your any "
    "'s accouring in the table with: str_replace("
    ", "\n", $textboxValue);
    –  Oct 15 '12 at 13:26
  • Hi. Not using any server side scripting since it will only save the file locally. – Alex M Oct 15 '12 at 14:07

2 Answers2

29
text = text.replace(/\n\r?/g, '<br />');

text is value from textarea.

14

The problem stems from the fact that line breaks (\n) are not the same as HTML <br /> tags.

Try this:

var text = document.forms[0].txt.value;
text = text.replace(/\n\r?/g, '<br />');

Edit, try this as the js:

var text = document.forms[0].txt.value;

if (text === true) { text = text.replace(/\n\r?/g, '<br />'); } 

var TestVar = new Array(i); 
var i = 0;
function save()
{
TestVar[i] = document.getElementById("text1").value + "/n" + document.getElementById("text2").value;
mydoc = document.open();
mydoc.write(TestVar);
mydoc.execCommand("saveAs",true,"TicketID.txt");
mydoc.close();
}
bjb568
  • 11,089
  • 11
  • 50
  • 71
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
  • tried that and it giving me the error below. Webpage error details Message: 'document.forms.0.txt' is null or not an object Line: 4 Char: 1 Code: 0 – Alex M Oct 15 '12 at 14:11
  • Webpage error details Message: 'document.forms.0.txt' is null or not an object Line: 4 Char: 1 Code: 0 – Alex M Oct 15 '12 at 14:14
  • Thanks but not sure if I am doing it correctly. Still got the same error message. – Alex M Oct 15 '12 at 14:25
  • var text = document.forms[0].txt.value; function replaceText() { if (text == true) { text = text.replace(/\n\r?/g, '
    '); } }
    – Alex M Oct 15 '12 at 14:25