This is an extension of a previous question I asked. I ran into some additional issues.
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:
updateTextareaText("myTextarea", "${myRequestParameter}");
From my previous question, I’ve found that this solves some issues:
updateTextareaText("myTextarea", unescape('<c:out value="${myRequestParam}" />'));
I have tried a number of different implementations for updateTextareaText, but nothing seems to work. I need to handle both newlines and special characters.
Try #1
function updateTextareaText(textareaElementName, newText) {
var textareaBox = document.getElementsByName(textareaElementName)[0];
textareaBox.innerHTML = newText;
}
Try #2
function updateTextareaText(textareaElementName, newText) {
var textareaBox = document.getElementsByName(textareaElementName)[0];
textareaBox.value = newText;
}
Try #3
function updateTextareaText(textareaElementName, newText) {
var textareaBox = document.getElementsByName(textareaElementName)[0];
var existingNodes = textareaBox.childNodes;
if (existingNodes.length > 0) {
textareaBox.removeChild(existingNodes[0]);
}
var newTextNode = document.createTextNode(newText);
textareaBox.appendChild(newTextNode);
}
All of the above loose newlines and/or displays some special characters as their escaped values. I’ve been using the following myRequestParam value for testing:
Test
Newline and Special `~!@#$%^&*()_+-={}|[]\:";'<>?,./
Does anyone know the correct way to handle all of the different cases? As a side note, the myRequestParam values are populated from the DB and are returning newlines as \r\n which I have been escaping as %0A, but I am not sure if that’s what I should be doing. The JavaScript originally wouldn’t handle the \r\n (it would complain about unterminated strings, etc).
See another question that I submitted. The trick was to remove the escaping from the backside and the whole
escapeand<c:out>stuff and instead use an EL function that utilizesStringEscapeUtils.escapeJavaScript.