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,778
  • 5
  • 33
  • 52
user2185012
  • 25
  • 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
  • 48,619
  • 13
  • 99
  • 109
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,722
  • 7
  • 36
  • 66