Home > Net >  How can i get This textarea value (content) into DIV like this format
How can i get This textarea value (content) into DIV like this format

Time:10-26

Here is a simple text area and button, i am trying to sending text area value (content) into <div id="rs"></div> with every separate line of textarea box (it means when we Enter button or Line breaks comes then all lines) appending to div into separate new element.

for example after clicking on addText button i want my output structure like this:

<div id="rs">
<div class='rslines'> first line of textarea- abc </div>
<div class='rslines'> second line of textarea- def </div>
<div class='rslines'> third line of textarea- ghi </div>
..... and so on
</div>

What i should change in my code:

$('#addtext').click(function(){
    var content = $("#cmt_content").val().replace(/(\n|\r|\r\n)/g, "<div class='rslines'></div>");
    $('#rs').append(content);
});
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  
  <textarea id="cmt_content" rows="10" cols="60"></textarea>
    <br> 
    <button id="addtext">
    addText
    </button>
    
<div id="rs"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

simply at this time i am getting all line outside of <div class='rslines'> </div> But i want all lines inside of this div.

CodePudding user response:

Instead of matching newlines, match all the content on a line instead - with . , you'll match any characters but newlines, and then you can replace with <div class='rslines'>$&</div> to put the matched text of each line inside <div>s.

$('#addtext').click(function(){
    var content = $("#cmt_content").val().replace(/. /g, "<div class='rslines'>$&</div>");
    $('#rs').append(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  
  <textarea id="cmt_content" rows="10" cols="60"></textarea>
    <br> 
    <button id="addtext">
    addText
    </button>
    
<div id="rs"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related