Is it possible to include parameters within a print() function in JavaScript?

Can anyone help me figure out how to add parameters to a print function? I only want to print a specific table, but when I try to print it, the entire page gets printed instead.

Here's my code:

let tableContent = document.getElementById('tablename').innerHTML

When I alert(tableContent), it shows the correct value. However, when I try to print(tableContent), the entire page is printed. I've also tried using print(tableContent) and tableContent.print, but neither of these solutions work.

If anyone knows the solution to this problem, I would greatly appreciate the help!

Answer №1

Using Javascript, you can achieve printing functionality without relying solely on print stylesheets. By passing the desired value to the function below, you can easily print the content.

function printIt(printThis) {
  var win = window.open();
  self.focus();
  win.document.open();
  win.document.write('<'+'html'+'><'+'body'+'>');
  win.document.write(printThis);
  win.document.write('<'+'/body'+'><'+'/html'+'>');
  win.document.close();
  win.print();
  win.close();
}

Answer №2

Create a specialized print stylesheet that will exclusively show the table content.

The print stylesheet does not need to be dynamic in nature.

You can simply use the display:none property to hide sections that are not necessary for printing (as advised in the designshack article).

Answer №3

To fulfill the functionality you requested, we can utilize a tabular view in the generated PDF document. In this scenario, I define a table with the ID "tableId" and then populate it with the necessary data:

printTableData(tableId) {
    let container = document.getElementById('tableId');
    let htmlData = 
        '<style type="text/css">' + 
        'table {'+'font-family: arial, sans-serif;'+ 
        'border-collapse: collapse;'+'width: 95%;'+ 
        'margin-left: 20px'+'}'+   
        'th, td {' +
        'border:1px solid #000;' +
        'padding: 8px;' +
        '}'+ 'tr:nth-child(even) {'+
        'background-color: #dddddd;'+'}'+
        '</style>';
    htmlData += container.outerHTML;
    let printWindow = window.open("");    
    printWindow.document.write(htmlData);
    printWindow.print();
    printWindow.close();
}

Answer №4

Sorry, that's not possible.

One solution could be adjusting a print media stylesheet dynamically to hide specific elements that you don't want to be printed.

Check out YUI StyleSheet for assistance with this task.

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

Display a div using JavaScript when the mouse moves and make it follow the cursor

In my application, I have a set of customer records displayed as rows in a table. I am looking to implement a feature where, upon hovering over a record (row), a div will pop up showing more detailed information about that specific record. This hover-over ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (w ...

Enhancing functionality in Javascript by employing prototype descriptor for adding methods

Code: Sorter.prototype.init_bubblesort = function(){ console.log(this.rect_array); this.end = this.rect_array.length; this.bubblesort(); } Sorter.prototype.init = function(array,sort_type){ this.rect_array = array; this.init_bubblesort(); } Wh ...

While working in Next.js, I utilized an `<Image />` tag with a link to an image, only to encounter an unexpected error

I've attempted it numerous times, but the error persists. I even went ahead and created the next.config.js file. module.exports = { images: { domains: ['link.papareact.com', ], }, }; Error: The src prop (https://links.pap ...

Error message "Exceeded the maximum call stack size" encountered during Vue-router authentication

I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged ...

Using jQuery to locate and delete multiple attributes from div elements

My goal is to locate all div elements with the class name "comment-like" that also have data-id attributes set to 118603,1234,1234,118601,118597. If a div contains any of these data values, then I want to remove that data attribute. I've attempted th ...

State values in React are found to be empty when accessed within a callback function triggered by

I have the following component structure: const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleUserKeyPress = useCallback((event) => { if (event.keyCode === 13) { doLogin( ...

Tips for handling Ajax urlencode in PHP

I'm facing an issue with a problem and need some assistance to resolve it. Currently, I am attempting to utilize Ajax urlencode in PHP, but the POST content is not being displayed by PHP as expected when HTML is sent directly to PHP. The following c ...

JavaScript Language Conversion Templating

I'm currently revamping the frontend for Facebook's internationalization XFBML tag, which has been nonfunctional for a while. I'm almost done with the updates but I have hit a roadblock: swapping out tokenized translations without losing dat ...

My selection of jQuery multiselect is experiencing issues with enabling disabled options

Incorporating the chosen jQuery plugin into my project has presented me with a challenge. The issue at hand is listed below. I have implemented a dropdown menu that includes both continents and countries in the same list. The specific scenario I am encou ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

I am having difficulty in crafting a sign-up form accurately

In my HTML file, I have a box that includes a sign-up form: <!-- sign up form --> <div id="cd-signup"> <form class="cd-form" action = "signup.php" > <?php echo "$error" ?> <p clas ...

Using async/await in an Express route handler

Currently, I am facing an issue with my node/express route. The route collects information through url parameters and then uses these parameters to trigger a separate function that takes some time to execute. Despite using async/await to pause the executio ...

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

Incorporate a new style into several previous slides using the Slick carousel feature

I'm attempting to utilize the Slick carousel to create a timeline. My goal is for the previous slides to remain colored as you progress through the timeline, and turn grey when you go back. I've tried using onAfterChange and onBeforeChange, but I ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Using CSS in combination with AngularJS, you can create a dynamic growth effect for a div element that initially

I am currently using AngularJS to dynamically add divs to a section. My goal is to have each div start with a static width and then grow dynamically as I continue to add more divs. How can I achieve this? The following code is not producing the desired re ...

JavaScript API for Tableau

Could you please clarify the functions described below? newViz = createTableauViz(containerDiv, url, options); function listenForMarkSelection() { newViz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, handleMarksSelection); } funct ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...