Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing HTML string to JavaScript function

I have a value that I'm currently accessing and passing to a JavaScript function through an onclick.

<a href="#" onclick="openTextWindow('<%=myVar.varDefinition.getText()%>');">Text</a>

An example value that I'd receive from the getText method is shown below.

<h1>My Header</h1><br />My text

This value is then passed to my openTextWindow method.

function openTextWindow(inText) {
    myWindow = window.open('','','width=500, height=300');
    myWindow.document.write(inText);
    myWindow.focus();
}

For some reason, the value stored in inText doesn't match the string with HTML tags that I showed above. It ends up looking like this.

"<lt/>h1<gt/>My Header<lt/>/h1<gt/><lt/>br /<gt/>My text

When inText is written to myWindow, I want that new window to render with the text My Header within a styled header and My text on a line below that. I've tried replacing and escaping characters with no luck. Any ideas on how to fix this or a better way to accomplish what I'm trying to do? Thanks!

like image 581
Adam Selene Avatar asked Sep 03 '25 04:09

Adam Selene


1 Answers

You can stash your HTML in a hidden DIV or textarea, then grab that from your function instead of trying to pass it inline.

<a href="#" onclick="openTextWindow('DIV1');">Text</a>
<div id="DIV1" style="display:none"><%=myVar.varDefinition.getText()%></div>

JS:

function openTextWindow(divName) {
    var inText = document.getElemenyById(divName).innerHTML;
    myWindow = window.open('','','width=500, height=300');
    myWindow.document.write(inText);
    myWindow.focus();
}
like image 77
Diodeus - James MacFarlane Avatar answered Sep 06 '25 01:09

Diodeus - James MacFarlane