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?

1

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Sam, your solution did work! Cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.