I have a form that users fill out which contains a textarea. This form is uploaded to a MySQL database, and then later the user can edit the info. The issue I am having is that when I use AJAX to suggest data for the textarea, javascript gives a "Invalid or unexpected token" error wherever a newline appears.
In the suggestion box it is a list with rows like so...
<li onClick="selectBenefiting('$benefiting')">$benefiting</li>
And selectBenefiting() is written like this...
function selectBenefiting(val) {
$("#benefiting").val(val);
$("#benefiting-sugg").hide();
}
Can anyone help me achieve this while preserving the line breaks? I have been searching for hours, and while I see other people with the same issue, I have yet to find a solution.
As I've said, it is a MySQL database. If I echo the data in the textarea using PHP it displays correctly, so I know it is in the database correctly. The issue is when using jQuery and AJAX to attempt to populate the textarea.
Any help would be greatly appreciated.
UPDATE:
$benefiting_js = str_replace("
", "\\
", $benefiting);
Slightly modified solution from Nick did the trick.
The problem is that Javascript doesn't like newlines in strings. So where you have them, you need to escape the newline characters. Try something like
$benefiting_js = str_replace("
", "\
", $benefiting);
And then change your <li>
to
<li onClick="selectBenefiting('$benefiting_js')">$benefiting</li>