1

I am trying to print a dialog box. I am able to print everything from the dialog box except the Textbox values.

HTML

<div class="calculator">
 <a href="#" onclick="printElement('.calculator')">
   <img src="images/icon_print.png" /> Print
 </a>
</div>

JS

function printElement(element) {
    var text = document.getElementById("age_input").value;
    alert(text);
    w = window.open();
    w.document.write($(element).html());
    w.document.close();
    document.getElementById("age_input").value = text;
    w.print();

    w.close();
}

How do I print the dialog with the values in the Textbox elements included?

doug65536
  • 6,014
  • 2
  • 37
  • 51
Nalini
  • 193
  • 2
  • 11
  • document.write: http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice –  May 18 '16 at 01:14

1 Answers1

1

Good question. It took me a while to figure it out. The issue is that the content of the text box is not part of HTML when you use $(element).html()

You can see this by inspecting the element by any browser dev tools (F12). Therefore you must make your content part of HTML to make them available during print. A quick workaround is to use placeholder attribute of the input box. Here's an updated version of your code.

<script type="text/javascript">
     function printElement(element) {
         var text = document.getElementById("age_input").value;
         document.getElementById("age_input").placeholder = text;
         w = window.open();
         w.document.write('<html><head><title>DIV Contents</title>');
         w.document.write('</head><body >');
         w.document.write($(element).html());
         w.document.write('</body></html>');
         w.document.close();
         document.getElementById("age_input").value = text;
         w.print();

         w.close();
     } 
 </script>

I assume age_input is your input box and it's within the Div element

<div class="calculator">
        <input id="age_input" type="text" />
 <a href="#" onclick="printElement('.calculator')"> <img src="images/icon_print.png" />Print</a>
 </div>
Pang
  • 8,605
  • 144
  • 77
  • 113
Sam
  • 2,818
  • 1
  • 12
  • 28