Having difficulty with printing a particular div

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!

Answer №1

It appears that there may be issues with currentAnsArray, as everything else seems to be working fine with jquery-1.11.3.min.js when I use the following code:

var currentAnsArray = ["Increased anger issues","Health problems & medical conditions"];

Instead of:

var currentAnsArray = <?php $newArray1 = explode("|",$ans[0]); echo json_encode($newArray1); ?>;

Try logging currentAnsArray to see what it contains.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Replicate styling while copying CodeMirror code

Is there a way to maintain the styling and formatting of javascript code when copying from CodeMirror? Whenever I try to copy and paste from the CodeMirror editor, the coloring and style are lost, with the content pasted as text/plain. How can I preserve ...

What are the steps for incorporating a linear-gradient hue into a Slider?

Is it possible to apply a linear-gradient as color to Material-UI Slider? I have tried everything but can't seem to make it work. color: 'linear-gradient(180deg, #29ABE2 0%, #00EAA6 100%)' ...

Is there a datatable available for live data with pagination and search functionality?

I've been experimenting with datatables for real-time data, but I'm facing an issue where the search function doesn't work when my data updates. Additionally, every time I try to paginate, it reverts back to the first page. Does anyone know ...

What is the approach for incorporating JavaScript variables in Jade templates for writing inline CSS styles?

Struggling to inject CSS code dynamically? You're not alone. style(type='text/css') #header a#logo { background:url(constants.logo) no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 1.5) { #header a#logo { ...

Hide the search results if the user leaves the input field blank

I am trying to implement Live Search JSON Data Using Ajax jQuery, and I want to be able to search through multiple JSON files. When the page initially loads with an empty input field, no results are displayed. However, if you type and then delete text in ...

Ensuring the width of a div matches the adjacent containers

I need assistance in creating a form that adjusts its width based on the form fields. The form contains both explanatory text and input fields, each enclosed in a div with inline-block set. The outer div (also using inline-block) should not expand beyond ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

Converting Javascript game information into PHP

Once the player loses, I need their score to be updated in the database using PHP. There is a separate JavaScript class that runs the game, utilizing setInterval to check the index.php function and update the database if the player loses. However, the issu ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...

What issue is present with this AJAX query?

Can you help me figure out where I went wrong with this AJAX code example that I'm trying to learn from? function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new ...

Is it possible to create an HTML dropdown menu with integer values?

What is the best way to create a dropdown menu in HTML with integer values ranging from 1 to 12? How can I ensure that when a value is selected, it gets saved into a variable? All I need is a simple select field in HTML that displays options from 1 to 12 ...

Angularjs scope's parent id

I'm looking to access or manipulate a scope's grandparent without making things overly complicated. Leveraging the controller as syntax, I can reference the parent controller like so: this.applicationCtrl.something with applicationCtrl > paren ...

The test() function in JavaScript alters the output value

I created a simple form validation, and I encountered an issue where the test() method returns true when called initially and false upon subsequent calls without changing the input value. This pattern repeats with alternating true and false results. The H ...

Is there a way to extract a username from LDAP?

Can you help me understand how to dynamically retrieve a username from LDAP? In the code snippet below, I have hardcoded the username as 'smith2': $_SERVER["REMOTE_USER"] = 'smith2'; $param = $_SERVER["REMOTE_USER"] By using this appr ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

Error arising from attempting to compile React animations for a specific component, rc

As someone new to React, I decided to try running a sample example from the following link: To do this, I created a file named MonApp.js with the code snippet below: import React, { Component } from 'react'; import { render } from "react-dom"; ...

Troubleshooting a Custom Menu Control in HTML

Would you mind taking a look at the menu I have set up in this fiddle: http://jsfiddle.net/Gk_999/mtfhptwo/3 (function ($) { $.fn.menumaker = function (options) { var cssmenu = $(this), settings = $.extend({ title: "Menu", ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

When text is added to div elements, they are mysteriously pushed downward. This strange phenomenon occurs with inline-block elements

Why does the first element get pushed down when its child contains text? What causes inline-block to behave this way? Is there a way to align divs side-by-side while still allowing them to have children? For example, I want the grey box to contain a list ...