Interaction design • webdevelopment • web art • photography : forum : coding : 'javacript, line carriage, new line'

javacript, line carriage, new line user 4574, 050608 20:21
first i have a text area as such:
<textarea cols="50" rows="6" name="body" style="font-family: monospace;" onkeyup="javascript:InsertBR();"></textarea>
then i have the javascript function 'InsertBR()':
function InsertBR()
frm_AddItem.body.value = frm_AddItem.body.value.replace(/\r\n/g," <BR/>\r\n");
as you can see, the form name is "frm_AddItem". when some presses enter, a <BR/> tag is inserted. in here, it is inserted everytime a character is pressed, i know how to make is so that its only the enter button, but what i dont know how to fix is the insertion of <BR/> tags everytime it finds the new line / carriage return. i want the output to insert the <BR/> tag but still go to a new line in the textarea. how would i do that?

i tried to do other stuff like this:
frm_AddItem.body.value.replace(/\r/g," <BR/>\n");
frm_AddItem.body.value.replace(/\n/g," <BR/>\n");
but it still puts multiple <BR/> tags.
Re: javacript, line carriage, new line Calm_Pear, 050610 11:09
Better do this kind of thing in a server side script... what are you using? php?
Re: javacript, line carriage, new line Jan!, 050612 21:08
First of all, "<BR/>" doesn't exist. You're mixing HTML or tag soup with XML syntax. There's no tag defined as "BR" in XHTML, only "br". And even then I doubt your JavaScript syntax is 100% kosher, what with the "frm_AddItem.body". Best use document.getElementById('myTextArea') or some such.

Secondly, about your real problem. From what I understand, you want the textarea to automagically contain both a <br> and an actual newline. Your function does not take previously added <br>'s into account, and as such the number of <br>'s keeps on increasing. Try this:

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

Warning: untested code, I don't give any guarantees. :-)
Pages: 1