I am trying to use javascript to print out a text field from a dbase where the textfield is served by php to a textarea that has an id. The print javascript function takes the content from the textarea using getElementById and prints it. But here is the issue. To display properly in the textarea, the textfield has newlines in it. These are invisible in the textarea. They just show up as line breaks. (They are also invisible using PHP admin in the dbase tables. They show up there as linebreaks as well).
However, to get the linebreaks to show up when you print the text, they need to be converted into <br>. Otherwie, you see and print a runown sentence.
I think I need to search for something in the javascript variable, perhaps \n and replace with
However, I can’t seem to get linebreaks to display in printed page (wich is html based.)
Can anyone suggest right way to do this? Thanks.
Flawed code:
js
f
unction printit(id) {
var toprint = document.getElementById(id).innerHTML;
toprint = toprint.replace("\n","<br>");
win = window.open();
self.focus();
win.document.open();
win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
win.document.write(toprint);
win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
win.document.close();
win.print();
win.close();
}
html
<textarea id="textarea">A whole bunch
of text
with line breaks
goes here
</textarea><a href="javascript:void(0);" onclick="printit('textarea');">Print text</a>
You’re probably only replacing the first line break. Try the global flag to replace them all: