Jarich Jarich - 22 days ago 6
HTML Question

How to get input values from print preview using jquery/javascript

I have this sample html content with fields
I need to print all content including input values and display it on sample preview.
I tried this script to trigger the print:

The sample printing is working fine however, the input values is not displaying. How can I achieve that? Should I use alternative other than html() function?



function PrintPreview() {
printWindow = window.open("", "", "location=1,status=1,scrollbars=1,width=650,height=600");
printWindow.document.write($('#mainbody').html());
printWindow.document.close();
printWindow.focus();
}

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<div id="mainbody">
Last Name
<input type="text" id="lname" name="lname">First Name
<input type="text" id="fname" name="fname">Middle Name
<input type="text" id="mname" name="mname">
</div>
<input type="button" onclick="PrintPreview();" value="Print Preview" />




Answer

This works for me - copy the value to the value attribute and clone the div

function PrintPreview() {
  $("#mainbody > input").each(function() { 
    $(this).attr("value",$(this).val()); 
  });

  var printWindow = window.open("", "_blank", "location,status,scrollbars,width=650,height=600");
  if (printWindow) {
    printWindow.document.write($('#mainbody').clone(true)[0].innerHTML);
    printWindow.document.close();
    printWindow.focus();
  }
  else alert("Please allow popups");
}