2011-12-09 85 views
0

這是我詢問的previous question的擴展。我遇到了一些其他問題。使用JavaScript填充Textareas

我正在加載一個帶有動態textarea框的表單。不要問爲什麼,但我需要使用JavaScript來填充這些字段(必須處理AJAX的東西等)。爲了簡化事情,我們只需說我的textarea的名稱是「myTextarea」,我想填充一個請求參數「myRequestParam」。所以,我願意做這樣的事情:

updateTextareaText("myTextarea", "${myRequestParameter}"); 

從我剛纔的問題,我發現,這解決了一些問題:

updateTextareaText("myTextarea", unescape('<c:out value="${myRequestParam}" />')); 

我已經嘗試了多種不同的實現方式爲updateTextareaText,但似乎沒有任何工作。我需要處理換行符和特殊字符。

嘗試#1

function updateTextareaText(textareaElementName, newText) { 
    var textareaBox = document.getElementsByName(textareaElementName)[0]; 
    textareaBox.innerHTML = newText; 
} 

嘗試#2

function updateTextareaText(textareaElementName, newText) { 
    var textareaBox = document.getElementsByName(textareaElementName)[0]; 
    textareaBox.value = newText; 
} 

嘗試#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); 
} 

所有上述鬆散換行符的nd /或顯示一些特殊字符作爲它們的轉義值。我一直在使用測試以下myRequestParam值:

Test 

Newline and Special `[email protected]#$%^&*()_+-={}|[]\:";'<>?,./ 

有誰知道正確的方式來處理所有的不同的情況?作爲一個側面說明,myRequestParam值從數據庫填充,並返回換行符爲\r\n,我一直在逃避作爲%0A,但我不知道這是我應該做的。 JavaScript最初不會處理\r\n(它會抱怨未終止的字符串等)。

回答

1

請參閱我提交的another question。訣竅是消除背面和整個escape<c:out>東西的逃逸,而是使用利用StringEscapeUtils.escapeJavaScript的EL功能。

0

嘗試的jQuery:

$('#textAreaId').val('MyValue'); 

$('#textAreaId').html('MyValue'); 

猜猜它會做的伎倆。

+0

我的公司還沒有批准jQuery使用。出於好奇,jQuery是否允許通過名稱(不是id)獲取? –

+0

哦,這樣的痛苦! jQuery它非常棒,可以節省大量時間...並且可以,在jQuery中您可以通過id,名稱,類,內容獲取任何項目...查看http://api.jquery.com/category/選擇/ – ricardordz

0

在一個有限的和本地的嘗試它爲我工作與您的#2功能(只有嘗試過那一個)。 !

頭:<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

的javascript:updateTextareaText( 「txtarea」,「測試\ n \ nNewline和特殊`\〜!@#$%\^\ & *()_ + - = {} | [ ] \:\ 「;」 <>,// \näöüÄÖÜß?」);

所以,你得到的字符串可能是沒有逃脫(\',\ &等),在這種情況下Apache的在下議院StringEscapeUtils Langs幫助(http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringEscapeUtils.html#escapeJavaScript%28java.lang.String%29)。

除此之外,你必須做一個轉換爲這個javascript案例通過替換'與\'等等...不漂亮。