Mike
Mike

Reputation: 2900

Inserting text with new lines into a textarea

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'];
}
?>

Upvotes: 3

Views: 16086

Answers (2)

Niemand
Niemand

Reputation: 346

$('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.

Upvotes: 7

Dedawn
Dedawn

Reputation: 80

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

Upvotes: -3

Related Questions