3

I am trying to insert data from a database into a textarea. I can't figure out how to make new lines though. I am using jquery's val() function to set the textarea content. I put \n but it just shows up in the textarea instead of making a newline. I have also tried \r\n with the same result.

UPDATE

Ok, I noticed if I just hardcode a string with \n in the val() function that it works. So the problem must be somewhere with the string I am returning via ajax from php. I am using $.ajax to call PHP which gets the value from mysql. Any ideas on what is going wrong?

HTML

<textarea id='topContent' class='divContent' rows='8'></textarea>

JAVASCRIPT

<script>
$('#dialogDiv').on('submit', '#insertMacroForm', function(){
    $.ajax({
        url: 'index.php',
        data: 'request=loadMacro2&id='+$('#macroSelection').val(),
        success: function(msg){
            $('#topContent').val(msg);
        }
    });
    return false;
});
</script>

PHP

<?php
$query = 'SELECT * FROM POEMACRO WHERE POEID=' . db2_escape_string($_GET['id']);
$result = db2_exec($conn, $query) or die(db2_stmt_errormsg());
while($row = db2_fetch_assoc($result)){
    print $row['POEMACRO'];
}
?>
Mike
  • 2,862
  • 10
  • 42
  • 55

2 Answers2

7
$('textarea').val('line1\nline2')

This works fine. You need to use \n in your JavaScript string.
If this string is formed in PHP on server, you may need something like json_encode() to format the string in JavaScript format.

Niemand
  • 346
  • 2
  • 10
  • The string is formed with php and returned via ajax. I just tried json_encode and now in the textarea \n shows up as \\n – Mike Jun 27 '12 at 12:35
  • Your answer led me in the right direction. I ended up adding double quotes around the string in php to make it a proper json string(without using json_encode) then I had to add $.parseJSON(msg) to my javascript. – Mike Jun 27 '12 at 13:31
-3

You need to parse through your text and convert the \n to break tags <br/> before you pass it to the textarea.

Dedawn
  • 80
  • 4