HTML - interrupt string in the pre-tag

I am trying to copy (with jQuery and JS) text written in textarea into a pre-tag. However, I cannot enter as many line breaks as I want. For example, if I press Enter once, it works, and I create a line break, but if I press Enter more than once, I cannot get more than one line break. Do you know why this is happening, or how can I fix it?

The code looks something like this:

<textarea id="area" rows="5" cols="30"> </textarea> <pre id="area2" > </pre> <br/> <script> newText = $( '#area' ).val(); $( '#pre' ).text( newText); </script>` 

The text field identifier is #area and the previous tag identifier is #pre

+4
source share
2 answers

I had this problem with IE7. It does not display more than one new line inside the pre-tag.

+1
source

Have you tried to do

 $( '#pre' ).html( newText); 

instead of this? It is possible that .text removes \n 's

If this does not work, I found the answer to similar questions here in the section "Stack Overflow", which may work for you. However, this is somehow a pain, because you need to write a rather large function that detects new lines and replaces them:

  //Based off <textarea id="text" cols="50" rows="5" style="overflow: scroll">This is a test sentence, with no newline characters in it, but with an automatically wrapped sentence that spans three lines.</textarea> var words = $("#text").val().split(" "); var cols = $("#text").attr("cols"); var text = ""; var lineLength = 0; for (var i = 0; i < words.length; i++) { var word = words[i]; if ((lineLength + word.length + 1) > cols) { text += "\n"; lineLength = 0; } else if (lineLength > 0) { text += " "; lineLength++; } text += word; lineLength += word.length; } $( '#pre' ).text(text); //Alerts: //This is a test sentence, with no newline //characters in it, but with an automatically //wrapped sentence that spans three lines. 
0
source

Source: https://habr.com/ru/post/1336995/


All Articles