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" />
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");
}
Alternatively
How to print only one div content from html page using print button
You can put the code below before PrintPreview function:
$('input').each(function(){
$(this).keyup(function(){
$(this).attr('value',$(this).val());
});
});
That way the value attribute is changed on keyup and the preview will work fine.
This one try .
<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" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function PrintPreview() {
window.print();
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.