Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulating Textareas with JavaScript
    text
    copied!<p>This is an extension of a <a href="https://stackoverflow.com/questions/8346198/javascript-escaping-form-values">previous question</a> I asked. I ran into some additional issues.</p> <p>I am loading a form with dynamic textarea boxes. Don't ask why, but I need to populate these fields using JavaScript (has to deal with AJAX stuff, etc). To simplify things, let's just say my textarea has a name of "myTextarea" and I want to populate with a request parameter "myRequestParam". So I'd want to do something like:</p> <pre><code>updateTextareaText("myTextarea", "${myRequestParameter}"); </code></pre> <p>From my previous question, I've found that this solves some issues:</p> <pre><code>updateTextareaText("myTextarea", unescape('&lt;c:out value="${myRequestParam}" /&gt;')); </code></pre> <p>I have tried a number of different implementations for <code>updateTextareaText</code>, but nothing seems to work. I need to handle both newlines and special characters.</p> <p><strong>Try #1</strong></p> <pre><code>function updateTextareaText(textareaElementName, newText) { var textareaBox = document.getElementsByName(textareaElementName)[0]; textareaBox.innerHTML = newText; } </code></pre> <p><strong>Try #2</strong></p> <pre><code>function updateTextareaText(textareaElementName, newText) { var textareaBox = document.getElementsByName(textareaElementName)[0]; textareaBox.value = newText; } </code></pre> <p><strong>Try #3</strong></p> <pre><code>function updateTextareaText(textareaElementName, newText) { var textareaBox = document.getElementsByName(textareaElementName)[0]; var existingNodes = textareaBox.childNodes; if (existingNodes.length &gt; 0) { textareaBox.removeChild(existingNodes[0]); } var newTextNode = document.createTextNode(newText); textareaBox.appendChild(newTextNode); } </code></pre> <p>All of the above loose newlines and/or displays some special characters as their escaped values. I've been using the following <code>myRequestParam</code> value for testing:</p> <pre><code>Test Newline and Special `~!@#$%^&amp;*()_+-={}|[]\:";'&lt;&gt;?,./ </code></pre> <p>Does anyone know the correct way to handle all of the different cases? As a side note, the <code>myRequestParam</code> values are populated from the DB and are returning newlines as <code>\r\n</code> which I have been escaping as <code>%0A</code>, but I am not sure if that's what I should be doing. The JavaScript originally wouldn't handle the <code>\r\n</code> (it would complain about unterminated strings, etc).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload