I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view.
Below is the code snippet for printing the div:
$(function () {
$("#btnPrint").click(function () {
var contents = $("#printDiv").html();
var frame1 = $('<iframe />');
frame1[0].name = "frame1";
$("body").append(frame1);
var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
frameDoc.document.open();
//Create a new HTML document.
frameDoc.document.write('<html><head><title>DIV Contents</title>');
frameDoc.document.write('</head><body>');
//Append the external CSS file.
frameDoc.document.write('<link href="css/carousel.css" rel="stylesheet" type="text/css">');
frameDoc.document.write('<link href="css/activities_folder.css" rel="stylesheet" type="text/css">');
//Append the DIV contents.
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
frame1.remove();
}, 500);
});
});
The targeted div for printing includes checkboxes as shown below:
<div id="printDiv" >
// Checkboxes content here ...
</div>
<button id="btnPrint" value="Print" class="myPrintBtn">Print</button>
The jQuery code used to check the checkboxes dynamically on page load is as follows:
$(document).ready(function() {
var currentAnsArray = ["Increased anger issues","Health problems & medical conditions"];
$("input:checkbox[name=q1]").each(function(){
for(var n=0; n < currentAnsArray.length; n++)
{
if($(this).val() == currentAnsArray[n])
{
$(this).prop('checked', true);
break;
}
}
});
});
EDIT : Updated the currentAnsArray
array as suggested by @Ovchynnykov for better clarity of the issue.
Please assist me with resolving this problem. Thank you!