2

I am using Text area tag in html and i have to print the ingredients in separate lines but even on using enter key it is coming in a single line when i pass the value of text area to a variable and print it.

Following is my code snippet :

<div data-role="fieldcontain">
    <label for="name">Ingredients</label>
    <textarea rows="4" cols="50" id="new_ingredients">

    </textarea>
</div>

$( '#new_recipe' ).live( 'pagebeforeshow',function(event){
    var temp1 = $("#new_ingredients").val();
    $("#testing").text(temp1);
});

<div data-role="page" id="new_recipe">
    <div class="content" id="testing" ></div>
</div>

Please help me as to how could i get data in different lines when the user presses enter key.Thank you in advance.

Subedi Kishor
  • 5,906
  • 5
  • 35
  • 53
user2185012
  • 23
  • 1
  • 1
  • 4

2 Answers2

3

Use this:

$("#testing").html(temp1.replace(/\n\r?/g, "<br />"));

The characters that are represented by pressing the "enter" key in a textarea are represented with "\n" (sometimes with \r as well). But when displaying in HTML, they mean nothing more than a space, visually. To display these newlines, they need to be replaced with the HTML equivalent - <br /> elements.

Since <br /> elements are now being added to the #testing element's contents, you need to use .html(), not .text(). Otherwise, the HTML is escaped and won't display properly.

DEMO: http://jsfiddle.net/Wkbrn/2/

Ian
  • 50,146
  • 13
  • 101
  • 111
  • @knut i tried using the replace function but it is showing
    tag in the div content along with the string and still not coming in separate lines.
    – user2185012 Apr 09 '13 at 06:50
  • @user2185012 Did you use `$("#testing").html()` instead of `$("#testing").text()` like I suggested? That's required in order to display the `
    ` HTML properly, and I explained it in the answer
    – Ian Apr 09 '13 at 06:52
  • @knut : Yes , i wasnt using .html and hence it wasn't working . Thank you :) – user2185012 Apr 09 '13 at 07:03
  • for better coverage use `replace(/(\n|\r|\r\n)/g, '
    ')` not just `/\n\r?/g`
    – AbdelHady Nov 30 '13 at 18:20
0

Try this

<script src='http://code.jquery.com/jquery-latest.min.js'></script>
<div data-role="fieldcontain">
        <label for="name">Ingredients</label>
        <textarea rows="4" cols="50" id="new_ingredients">ingredient1&#13;&#10;ingredient2&#13;&#10
        </textarea>
        </div>

<script>
$(document).ready(function(){
var temp1 = $("#new_ingredients").html().replace(/\n/g,"<br>");;
 $("#testing").html(temp1);
})
</script>

<div data-role="page" id="new_recipe">
<div class="content" id="testing" ></div></div>

I have modified the script just for testing

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67