Replace multiple strings within textarea with jQuery
I have a working code that replaces multiple strings within a textarea. However it only replaces strings that are written onLoad in my textarea. I want to paste some text into the textarea and rep...
stackoverflow.com
js
$(".change").click(function() {
var dictionary= {
"Schwarz":"#000000",
"Braun":"#6F3E18",
"Beige":"#D4BE8D",
"Grau":"#838383",
"Weiß":"#FFFFFF",
"Dunkelblau":"#0000A0",
"Blau":"#345AFF",
"Hellblau":"#32CAEB",
"Türkis":"#22A2A4",
"Grün":"#25B53A",
"Gelb":"#FFFC00",
"Orange":"#FF6501",
"Rot":"#EA0001",
"Pink":"#ED008C",
"Hell Lila":"#9349AA",
"Dunkel Lila":"#663376",
"Mehrfarbig":"#mcol"
};
$("body *").each( function(){
for( var ptrn in dictionary){
$(this).val( $(this).val().replace(new RegExp(ptrn ,"g"), dictionary[ptrn] ) );
}
});
alert( "done" );
});
html
<input type="button" class="change" value="change all">
<textarea class="input">Schwarz -- doesn't work for text, that was pasted into textarea, onLoad text only....why???</textarea>
dictionary 말고도 jquery 의 each 함수를 통해 다중의 class 접근하여 해당 dom 의 값을 변경할 수 있습니다. textarea 는 값을 변경할 경우 text() 함수가 아닌 val() 로 변경이 가능합니다.
<pre>
<a id="send-thoughts" href="">Click</a>
<textarea id="message1" class="message">Hello</textarea>
<textarea id="message2" class="message">World</textarea>
</pre>
$("textarea.message").each(function () { this.value = this.value.replace(/,/g, "^"); })