Skip to content Skip to sidebar Skip to footer

Using Jquery How Can I Set The Contents Of A Textarea When The Value From Mysql Contains Newlines

To keep my code clean I am defaulting each of the elements of a form with jQuery. i.e My form contains elements like this.. I

Solution 1:

it could be single quotes instead of double quotes, try this:

echo PHP_EOL.'$("#notes").html("'.$user['notes'].'");';

Solution 2:

unterminated string literal

You're getting this message because in Javascript you can't span literal strings across multiple lines.

What you need to do is replace newlines in $user['notes'] with the characters \r\n so all the string is on one line then the <textarea> input will correctly show each item on a new line.

Let's use json_encode to help us also escape any nasty characters which Javascript won't like.

// This will convert to be Javascript friendly. // Output string will be enclosed in quotes " "$notes_str = json_encode($user['notes']);
echo"\n $('#notes').html(" . $notes_str . ");";

Solution 3:

Replace your line returns with \n, something like this:

echo"\n $('#notes').html('".str_replace("\n","\\n",$user['notes'])."');";

php is not my strongest suit, so the syntax may be slightly off. But basically replace the line returns with the characters "\n". (may need to handle /r too I guess, or a combination of the two)

EDIT: Apparently if you're using PHP 5.2 or greater you can use json_encode( and it will handle quotes and newlines.

Solution 4:

If you are using smarty templating engine you can use it like --

$('textarea#myTextAreaId').val({$arrVal.keyValue|@json_encode});

otherwise its common to face this problem as currently .val() on textarea elements strips carriage return.

Post a Comment for "Using Jquery How Can I Set The Contents Of A Textarea When The Value From Mysql Contains Newlines"